zoukankan      html  css  js  c++  java
  • 建造者模式

    模型图形:

                                 Director  -->  Builder

                                                        |

                                               ConcreteBuilder -----> Product

                                                 |        |       |                |   |

                                              ...     RealBuilder ..         .... RealProduct

    public abstract class Product {
    private ArrayList<String> sequence;
    protected abstract void doSomething1();
    protected abstract void doSomething2();
    public void setSequence(ArrayList<String> al){
    this.sequence = al;
    }
    public void doTheRealThing(){
    for(int i = 0;i<this.sequence.size();i++){
    if(this.sequence.get(i).equals("doSomething1")){
    this.doSomething1();
    }else if(this.sequence.get(i).equals("doSomething2")){
    this.doSomething2();
    }
    }
    }
    }

    public class RealProd1 extends Product {

    @Override
    protected void doSomething1() {
    // TODO Auto-generated method stub
    System.out.println("I am the doSomething1 in the RealProd1");
    }

    @Override
    protected void doSomething2() {
    // TODO Auto-generated method stub
    System.out.println("I am the doSomething2 in the RealProd1");
    }

    }

    public class RealProd1Builder implements Builder {
    private RealProd1 p;
    public void setSequence(ArrayList<String> al) {
    // TODO Auto-generated method stub
    p = new RealProd1();
    p.setSequence(al);
    }

    public Product getProduct() {
    // TODO Auto-generated method stub
    return this.p;
    }

    }

    public class Director {
    public Product getRealProd1(){
    ArrayList<String> al = new ArrayList<String>();
    al.add("doSomething1");
    al.add("doSomething2");
    Product p = new RealProd1();
    p.setSequence(al);
    return p;
    }
    public Product getRealProd2(){
    return null;
    }
    }

    测试方法:

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Director d = new Director();
    d.getRealProd1().doTheRealThing();
    }

    说明:产品侧的类定义和模板方法类似,只是通过arraylist来动态设置具体方法的执行顺序,

    建造侧类的定义:只有设置al和返回产品类。具体的al实例对象放到了director类来设置。故只要改director的al就可以控制prod的具体实现了。

  • 相关阅读:
    unity c# 获取系统时间
    如果你想让继承MonoBehaviour的类变成Singleten
    关于程序员
    开始养成记录的习惯吧
    关于结构体的赋值问题
    数学中的集合,群,环,域
    励志
    [编程题] 进制均值
    javaEE 入门
    jsp内置对象2
  • 原文地址:https://www.cnblogs.com/thinkqin/p/3812802.html
Copyright © 2011-2022 走看看