1.构造者模式
优点:实现了构建和装配的解耦。不同的构建器,相同的装配,也可以做出不同的对象;相同的构建器,不同的装配顺序也可以做出不同的对象。也就是实现了构建算法、装配算法的解耦,实现了更好的复用。
缺点:非常复杂,有很多步骤需要处理
2.模式实例
public class Car { private Engine engine; private Body body; private Wheel wheel; public Engine getEngine() { return engine; } public void setEngine(Engine engine) { this.engine = engine; } public Body getBody() { return body; } public void setBody(Body body) { this.body = body; } public Wheel getWheel() { return wheel; } public void setWheel(Wheel wheel) { this.wheel = wheel; } } public class Wheel { } class Body { } class Engine{ } public interface Builder { public abstract Wheel createWheel(); public abstract Body createBody(); public abstract Engine createEngine(); } public class SxtBuilder implements Builder { private static SxtBuilder sxtBuilder = new SxtBuilder(); @Override public Wheel createWheel() { return new Wheel(); } @Override public Body createBody() { return new Body(); } @Override public Engine createEngine() { return new Engine(); } private SxtBuilder() { super(); } public static SxtBuilder getSxtBuilder() { return sxtBuilder; } } public class SxtDerictor { public static Car getCar() { Car car = new Car(); SxtBuilder sixBuilder = SxtBuilder.getSxtBuilder(); car.setEngine(sixBuilder.createEngine()); car.setWheel(sixBuilder.createWheel()); car.setBody(sixBuilder.createBody()); return car; } } public class Client { public static void main(String[] args) { Car car = SxtDerictor.getCar(); } }
原文:https://www.cnblogs.com/gg128/p/9551769.html