类型和定义
工厂方法模式属于创造性设计模式。定义一个用于创建对象的接口,让子类决定实例化哪一个类。
建造者模式也是属于创造性设计模式。将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
举例说明
比如说需要制造一个超人
-
使用工厂方法模式来制造,直接生产出来的就是一个力大无穷、能够飞翔、内裤外穿的超人。
-
使用建造者模式,则需要组装头、手、脚、躯干等部分,然后再把内裤外穿,于是一个超人就出现了。
下面使用代码来实现
工厂方法模式实现
-
public interface ISuperMan {
-
/**
-
* 每个超人都有特殊天赋技能
-
*/
-
void spcialTallent();
-
}
-
public class BlackSuperMan implements ISuperMan {
-
@Override
-
public void spcialTallent() {
-
System.out.println("我是黑种人的超人,跳的非常高,刀枪不入");
-
}
-
}
-
public class YellowSuperMan implements ISuperMan {
-
@Override
-
public void spcialTallent() {
-
System.out.println("我是黄种人的超人,跳的非常高,刀枪不入");
-
}
-
}
-
public class SuperManFactory {
-
public static ISuperMan createSuperMen(String tye) {
-
if ("balck".equals(tye)) {
-
return new BlackSuperMan();
-
} else if ("yellow".equals(tye)) {
-
return new YellowSuperMan();
-
} else {
-
return null;
-
}
-
}
-
}
-
public class Client {
-
public static void main(String[] args) {
-
ISuperMan superMan = SuperManFactory.createSuperMen("yellow");
-
superMan.spcialTallent();
-
}
-
}
输出:我是黄种人的超人,跳的非常高,刀枪不入
建议一个生产超人的工厂,具体需要生产黑超人还是黄超人,都是超人。具体这个超人是怎么组装的、什么时候把内裤外穿的都不用关心。类似于咱们去买手机时候,只管跟卖家说你要买什么牌子的什么类型的手机就行了,不需要你知道手机是怎么生产出来的。
也就是说,工厂方法模式是一个产品整体,生产出来的产品应该具有相似的功能。
。。。。。。。。。。。。。。。。。
版权原因,完整文章,请参考如下:工厂方法模式VS建造者模式