工廠模式的產(chǎn)品角色和簡(jiǎn)單工廠并沒有區(qū)別。變化就是在工廠角色那。將具體創(chuàng)建產(chǎn)品的工作放到子工廠進(jìn)行。這樣就便于進(jìn)行擴(kuò)展了。
public interface IProduct {
public void desc();
}
public class ProductA implements IProduct {
public void desc() {
//excute;
}
}
public class ProductB implements IProduct {
public void desc() {
//excute;
}
}
public interface IFactory {
public IProduct factory();
}
public class FactoryA implements IFactory {
public IProduct factory() {
return new ProductA();
}
}
public class FactoryB implements IFactory {
public IProduct factory() {
return new ProductB();
}
}
個(gè)人覺得如果工廠的factory方法如果是靜態(tài)的也可以阿。為什么不呢?但是接口是無法申明static的方法的。只能用類或抽象類來做。不知道還有沒有更好的方法。
public abstract class IFactory {
public static IProduct factory(){return null;};
}
public class FactoryA extends IFactory {
public static IProduct factory() {
return new ProductA();
}
}
public class FactoryB extends IFactory {
public static IProduct factory() {
return new ProductB();
}
}