java设计模式创建模式Creational Pattern建造模式Builder Pattern
Posted xiongjiawei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java设计模式创建模式Creational Pattern建造模式Builder Pattern相关的知识,希望对你有一定的参考价值。
1 package com.tn.pattern; 2 3 public class Client { 4 public static void main(String[] args) { 5 Director director=Director.getInstance(); 6 director.construct(new ConcreteBuilder1()); 7 director.construct(new ConcreteBuilder2()); 8 } 9 } 10 11 class Director{ 12 static Director director; 13 private Director(){} 14 public static Director getInstance(){ 15 if(director==null) 16 director=new Director(); 17 return director; 18 } 19 public void construct(Builder builder){ 20 builder.buildPart1(); 21 builder.buildPart2(); 22 } 23 } 24 25 interface Builder{ 26 void buildPart1(); 27 void buildPart2(); 28 Product retrieveResult(); 29 } 30 31 class ConcreteBuilder1 implements Builder{ 32 Product product; 33 @Override 34 public void buildPart1() { 35 System.out.println("ConcreteBuilder1.buildPart1()"); 36 product=new Product1(); 37 } 38 39 @Override 40 public void buildPart2() {} 41 42 @Override 43 public Product retrieveResult() { 44 return product; 45 } 46 } 47 48 class ConcreteBuilder2 implements Builder{ 49 Product product; 50 @Override 51 public void buildPart1() {} 52 53 @Override 54 public void buildPart2() { 55 System.out.println("ConcreteBuilder2.buildPart2()"); 56 product=new Product2(); 57 } 58 59 @Override 60 public Product retrieveResult() { 61 return product; 62 } 63 } 64 65 interface Product{} 66 67 class Product1 implements Product{ 68 public Product1(){ 69 System.out.println("Product1.Product1()"); 70 } 71 } 72 73 class Product2 implements Product{ 74 public Product2(){ 75 System.out.println("Product2.Product2()"); 76 } 77 }
以上是关于java设计模式创建模式Creational Pattern建造模式Builder Pattern的主要内容,如果未能解决你的问题,请参考以下文章
原型模式(Prototype)-创建型(Creational)设计模式
编程思想设计模式创建模式creational抽象工厂模式abstract_factory