Design Pattern _ builder Pattern
Builder PatternSeparate the construction of a complex object from its representation so that the same construction process can create different representations. separates the construction of a complex object from its representation so that different representations can be created during the same construction process.
BenzModel inherits CarModel to implement business, but involves sequences.
The BenzBuilder class has a private property BenzModel. It sets the sequence method and obtains the BenzModel method. It sets the sequence through the Builder and obtains the object.
Product
public abstract class CarModel { private ArrayList
sequence = new ArrayList
(); public abstract void start(); public abstract void stop(); public abstract void alarm(); public abstract void engineBoom(); public void run() { for (int i = 0; i < sequence.size(); i++) { String actionName = sequence.get(i); if (actionName.equalsIgnoreCase(start)) { this.start(); } else if (actionName.equalsIgnoreCase(stop)) { this.stop(); } else if (actionName.equalsIgnoreCase(alarm)) { this.alarm(); } else if (actionName.equalsIgnoreCase(engineBoom)) { this.engineBoom(); } } } final public void setSequence(ArrayList
sequence) { this.sequence = sequence; }}
Public class BenzModel extends CarModel {@ Override public void alarm () {System. out. println (called by Mercedes-Benz);} @ Override public void engineBoom () {System. out. println (Mercedes);} @ Override public void start () {System. out. println (Mercedes-Benz startup);} @ Override public void stop () {System. out. println (Mercedes-Benz stopped );}}
Builder
public abstract class CarBuilder { public abstract void setSequence(ArrayList
sequence); public abstract CarModel getCarModel();}
// BenzBuilder extends CarBuilder {private BenzModel benz = new BenzModel (); // The key here is @ Override public CarModel getCarModel () {return this. benz;} @ Override public void setSequence (ArrayList
Sequence) {this. benz. setSequence (sequence );}}
It can be assembled at will.
public static void main(String[] args) { ArrayList
sequence=new ArrayList
(); sequence.add(start); sequence.add(stop); sequence.add(engineBoom); BenzBuilder builder=new BenzBuilder(); builder.setSequence(sequence); BenzModel benzModel=(BenzModel) builder.getCarModel(); benzModel.run(); }
AdvantagesGood encapsulation. It can be expanded independently only by notifying the customer of the use of the Rules.
Use CasesMultiple parts or parts in the same method and different execution sequence can be assigned to an object when different event results are generated, however, the running results are not both sequential.