创建者模式主要由5部分组成:抽象产品类、实现抽象产品类的具体类、抽象创建者类、实现抽象创建者类的具体类、组装类
?
说明:比工厂抽象工厂增加一个用来组装产品的类,客户端就不用知道对象的构建细节.
?
UML原理图:
?
?
?
例子:
?
package com.buider; public class Client { public static void main(String[] args){ Director diretor = new Director(new MotorcycleFactory()); Motorcycle m = diretor.assembleMotorcycle(); } } package com.buider; /** * * @Title: Director.java * @Description: 组装类 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public class Director { private Factory factory; public Director(Factory factory){ this.factory = factory; } //这里进行组装 public Motorcycle assembleMotorcycle(){ Wheel w = factory.createWheel(); w.bulid(); Tyre t = factory.createTyre(); t.bulid(); Engine e = factory.createEngine(); e.build(); return new Motorcycle1(); } } package com.buider; /** * * @Title: Engine.java * @Description: 发动机接口类 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public interface Engine { void build(); } package com.buider; public class Engine1 implements Engine { public void build() { System.out.println("组装摩托车发动机开始"); } } package com.buider; public interface Factory { Wheel createWheel(); Tyre createTyre(); Engine createEngine(); } package com.buider; /** * * @Title: Motorcycle.java * @Description: 摩托车类接口 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public interface Motorcycle { void bulid(); } package com.buider; /** * * @Title: Motorcycle1.java * @Description: 具体摩托车类 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public class Motorcycle1 implements Motorcycle{ public void bulid() { System.out.println("组装摩托车开始"); } } package com.buider; public class MotorcycleFactory implements Factory { public Engine createEngine() { return new Engine1(); } public Tyre createTyre() { return new Tyre1(); } public Wheel createWheel() { return new Wheel1(); } } package com.buider; /** * * @Title: Tyre.java * @Description: 摩托车轮胎接口类 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public interface Tyre { void bulid(); } package com.buider; /** * * @Title: Tyre1.java * @Description: 摩托车轮胎具体类 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public class Tyre1 implements Tyre { public void bulid() { System.out.println("组装摩托车轮胎开始"); } } package com.buider; /** * * @Title: Wheel.java * @Description: 车轮接口类 * @author awfhome@163.com * @date 2010-6-3 * @version V1.0 */ public interface Wheel { void bulid(); } package com.buider; public class Wheel1 implements Wheel { public void bulid() { System.out.println("组装摩托车轮开始."); } }
?
?
?
?
?
?
?