Builder mode: Separates the construction of a complex object from its representation so that the same build process can create different representations.
UML Class Diagrams:
Constitute:
1.Builder (interface/abstract Class) defines the method for creating individual parts of a product, returning the created product.
2.Director Call Builder to create a part to control the creation of the product
3.ConcreteBuilder Implement/Rewrite builder method, responsible for creating product individual parts
4.Product objects that are created
In the case of mobile phones, where builder uses abstract classes, provides an empty method as the default part creation method and creates, returns a product two methods, or can be defined as an interface for specific classes to implement
Abstract classBuilder { PublicPhone Phone {Get;Private Set; } Virtual Public voidCreatephone () {phone =NewPhone ();} Virtual Public voidaddcpu () {}Virtual Public voidaddmemory () {}Virtual Public voidAddscreen () {}Virtual PublicPhone Getphone () {returnphone; } }
A concretebuilder that generates an Apple phone
classApplebuilder:builder {Override Public voidaddcpu () {phone. CPU="A7"; } Override Public voidaddmemory () {phone. Memory="1GB"; } Override Public voidAddscreen () {phone. screen="LG 5.5\ ""; } }
Director is responsible for invoking builder
class Director { publicvoid Createphone (builder Builder) { builder.createphone (); Builder.addcpu (); Builder.addmemory (); Builder.addscreen (); } }
The product to be generated phone
classPhone { Public stringCPU; Public stringMemory; Public stringScreen ; Public Override stringToString () {return "CPU:"+cpu+"\nmemory:"+memory+"\nscreen:"+Screen ; } }
Execute code
Effect:
1. Change the product, just define a new ConcreteBuilder
2.Director the construction process of the product can be finely controlled (the order in which each part is created) What else? )
Design Pattern C # implementation (vii)--Generator mode