Java设计模式之建造者模式

代码转自:http://www.importnew.com/6841.html
建造者模式,使用不同的Builder,构建出形态不同的产品。与工厂模式最大区别在于,建造者模式最主要的功能是基本方法调用顺序的安排,而工厂方法重点在创建对象,不关心基本方法调用顺序


package com.pocketdigi.patterns.builder;

/**
 * 最终构建出的产品
 */
public class Starbucks {
    private String size;
    private String drink;
    public void setSize(String size) {
        this.size = size;
    }
    public void setDrink(String drink) {
        this.drink = drink;
    }
    
}

package com.pocketdigi.patterns.builder;
/**
 * 抽象建造者
 */
public abstract class StarbucksBuilder {
    protected Starbucks starbucks;

    public Starbucks getStarbucks() {
        return starbucks;
    }
    public void createStarbucks()
    {
        starbucks=new Starbucks();
        System.out.println("a drink is created");
    }
    
    public abstract void buildSize();
    public abstract void buildDrink();
}

package com.pocketdigi.patterns.builder;
/**
 * Tea建造者
 */
public class TeaBuilder extends StarbucksBuilder {

    @Override
    public void buildSize() {
        // TODO Auto-generated method stub
        starbucks.setSize("large");
        System.out.println("build large size");
    }

    @Override
    public void buildDrink() {
        // TODO Auto-generated method stub
        starbucks.setDrink("tea");
        System.out.println("build tea");
    }

}

package com.pocketdigi.patterns.builder;
/**
 * Tea建造者
 */
public class CoffeeBuilder extends StarbucksBuilder {

    @Override
    public void buildSize() {
        // TODO Auto-generated method stub
        starbucks.setSize("medium");
        System.out.println("build medium size");
    }

    @Override
    public void buildDrink() {
        // TODO Auto-generated method stub
        starbucks.setDrink("Coffee");
        System.out.println("build Coffee");
    }

}

package com.pocketdigi.patterns.builder;
/**
 * Builder封装
 */
public class Waiter {
    private StarbucksBuilder starbucksBuilder;

    public Starbucks getStarbucksDrink() {
        return starbucksBuilder.getStarbucks();
    }

    public void setStarbucksBuilder(StarbucksBuilder starbucksBuilder) {
        this.starbucksBuilder = starbucksBuilder;
    }
    
    public void build()
    {
        starbucksBuilder.createStarbucks();
        starbucksBuilder.buildDrink();
        starbucksBuilder.buildSize();
    }
}

调用:


        //建造者模式
        Waiter waiter=new Waiter();
        StarbucksBuilder starbuksBuilder=new TeaBuilder();
        waiter.setStarbucksBuilder(starbuksBuilder);
        waiter.build();
        Starbucks starBucks=waiter.getStarbucksDrink();

© 2014, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记

发表评论

电子邮件地址不会被公开。 必填项已用*标注