简单说就是有一个工厂,它生产多种产品,你指名要哪种产品,他就给你哪种产品。比如,小区边上有包子店,卖豆沙包,肉包,青菜包,香菇包等等,你过去,只要说你要哪种,老板就给你拿哪种。再比如,你去买洗面奶,有兰蔻的,olay,the face shop的。你要哪个,售货员给你拿哪个。这就是简单工厂能实现的,需求是一维的。
就是定义个一维数组就能完成。比如String baoZi = {"豆沙","鲜肉","青菜","香菇"};
String Cleanser = {"lancome","olay","the face shop"};
如果一维数组整不了,要二维的,那就得整抽像工厂了。
这里只说简单工厂,抽象工厂另一篇写。
java代码实现。
. 产品
public interface Cleanser{
}
.
public class LancomeCleanser implements Cleanser{
public cleanFace(){
System.out.println("Now you're using Lancome Cleanser!");
}
}
public class OlayCleanser implements Cleanser{
public cleanFace(){
System.out.println("Now you're using Olay Cleanser!");
}
}
//...... the face shop 不写了
//核心
public class CleanserFactory(){
public static Cleanser getCleanser(int i){
Cleanser c = null;
switch(i){
case 1: c = new LancomeCleanser(); break;
case 2: c = new OlayCleanser; break;
default : c = new TheFaceShopCleanser; break;
}
return Cleanser;
}
}
//测试类
public class TestSimpleFactory{
public static void main(String [] args){
CleanserFactory.getCleanser(1);
}
}
缺点:
hard code,来一个产品,就得在工厂里面再加个。