类型和定义
工厂方法模式属于创造性设计模式。定义一个及用于创建对象的接口,让子类决定实例化哪一个类。
建造者模式也是属于创造性设计模式。将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
举例说明
比如说需要制造一个超人
使用工厂方法模式来制造,直接生产出来的就是一个力大无穷、能够飞翔、内裤外穿的超人。
使用建造者模式,则需要组装头、手、脚、驱赶等部分,然后再把内裤外穿,于是一个超人就出现了。
下面使用代码来实现
工厂方法模式实现
publicinterfaceISuperMan{
/**
* 每个超人都有特殊天赋技能
*/
voidspcialTallent();
}
publicclassBlackSuperManimplementsISuperMan{
@Override
publicvoidspcialTallent() {
System.out.println("我是黑种人的超人,跳的非常高,刀枪不入");
}
}
publicclassYellowSuperManimplementsISuperMan{
@Override
publicvoidspcialTallent() {
System.out.println("我是黄种人的超人,跳的非常高,刀枪不入");
}
}
publicclassSuperManFactory{
publicstaticISuperMancreateSuperMen(Stringtye) {
if("balck".equals(tye)) {
returnnewBlackSuperMan();
}elseif("yellow".equals(tye)) {
returnnewYellowSuperMan();
}else{
returnnull;
}
}
}
publicclassClient{
publicstaticvoidmain(String[]args) {
ISuperMansuperMan=SuperManFactory.createSuperMen("yellow");
superMan.spcialTallent();
}
}
输出:我是黄种人的超人,跳的非常高,刀枪不入
建议一个生产超人的工厂,具体需要生产黑超人还是黄超人,都是超人。具体这个超人是怎么组装的、什么时候把内裤外穿的都不用关心。类似于咱们去买手机时候,只管跟卖家说你要买什么牌子的什么类型的手机就行了,不需要你知道手机是怎么生产出来的。
也就是说,工厂方法模式是一个产品整体,生产出来的产品应该具有相似的功能。
建造者模式实现
//超人模板
publicclassSuperMan{
privateStringbody;
privateStringspcialTalent;
privateStringspcialSymbol;
publicStringgetBody() {
returnbody;
}
publicvoidsetBody(Stringbody) {
this.body=body;
}
publicStringgetSpcialTalent() {
returnspcialTalent;
}
publicvoidsetSpcialTalent(StringspcialTalent) {
this.spcialTalent=spcialTalent;
}
publicStringgetSpcialSymbol() {
returnspcialSymbol;
}
publicvoidsetSpcialSymbol(StringspcialSymbol) {
this.spcialSymbol=spcialSymbol;
}
@Override
publicStringtoString() {
return"SuperMan{"+
"body='"+body+'\''+
", spcialTalent='"+spcialTalent+'\''+
", spcialSymbol='"+spcialSymbol+'\''+
'}';
}
}
publicabstractclassBuilder{
SuperMansuperMan=newSuperMan();
abstractSuperMancreateSuperMan();
}
//建造黑超人
publicclassBlackSuperManBuilderextendsBuilder{
@Override
publicSuperMancreateSuperMan() {
superMan.setBody("非常强壮");
superMan.setSpcialTalent("跑得非常快,刀枪不入");
superMan.setSpcialSymbol("黑色的");
returnsuperMan;
}
}
//建造黄超人
publicclassYellowSuperManBuilderextendsBuilder{
@Override
publicSuperMancreateSuperMan() {
superMan.setBody("非常强壮");
superMan.setSpcialTalent("跳的非常高,刀枪不入");
superMan.setSpcialSymbol("黄色的");
returnsuperMan;
}
}
//导演类
publicclassDirector{
publicstaticSuperMangetBalckSuperMan(){
returnnewBlackSuperManBuilder().createSuperMan();
}
publicstaticSuperMangetYellowSuperMan(){
returnnewYellowSuperManBuilder().createSuperMan();
}
}
publicclassCilent{
publicstaticvoidmain(String[]args) {
SuperMansuperMan=Director.getBalckSuperMan();
System.out.println("超人:"+superMan);
}
}
输出:
超人:SuperMan{body='非常强壮', spcialTalent='跑得非常快,刀枪不入', spcialSymbol='黑色的'}
可以看出建造者模式必须关注超人的各个部件,比如说你要去买手机,得自己拿着手机的组件一个一个的组装出一个手机来,而前面的工厂方法模式则只关注超人的整体。
意图不同
在工厂方法模式中,我们关注的是一个产品的整体,而在建造者模式中一个具体产品的产生是依赖各个部件的产生以及组装顺序,关注的是由一个一个零件装出来的产品对象。
简单的说,工厂方法模式是一个对象创建的粗线条应用,而建造者模式是通过细线条勾勒出来的复杂对象,关注的是产品组成部分的创建过程。