7. Builder, prototype, and Singleton of the Creation Mode ----- big talk design mode and the prototype of the two figures of the westward journey

Source: Internet
Author: User

7. Builder, prototype, and Singleton of the Creation Mode ----- big talk design mode and the prototype of the two figures of the westward journey

I. Builder Mode

Separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.

The benefit of the builder mode is to separate the Construction Code from the representation code. Because the builder hides how the product is assembled, if you need to change the internal representation of a product, you only need to define a specific builder.

This class is used to control the construction process and isolate the association between users and the construction process.

Builder: person

ConcreteBuilder1: fat man

ConcreteBuilder2: thin

Director: Start assembly

Product: Result

// A specific Product class. The final collection of the Product Style class Product {// The IList <string> parts = new List <string> (); // Add the public void Add (string part) {parts. add (part) ;}// list all product parts public void Show () {Console. writeLine ("\ n product creation ----"); foreach (string part in parts) {Console. writeLine (part );}}}

// Abstract Builder class, identify several parts, and return product abstract class Builder {// two parts constitute public abstract void BuildPartA (); public abstract void BuildPartB (); public abstract Product GetResult () ;}// Product A Implementation class ConcreteBuilder1: Builder {private product Product = new Product (); // assemble Part A into the product public override void BuildPartA () {product. add ("Part A") ;}// assemble Part B to the product public override void BuildPartB () {product. add ("Part B") ;}public override Product GetResult () {return product ;}/// Product B Implementation class ConcreteBuilder2: builder {private Product product = new Product (); public override void BuildPartA () {product. add ("Part X");} public override void BuildPartB () {product. add ("part Y") ;}public override Product GetResult () {return product ;}}
// Conductor class Director {public void Construct (Builder builder) {// create part A builder. BuildPartA (); // create part B builder. BuildPartB ();}}
// Client code static void Main (string [] args) {// initialize a conductor Director ctor = new director (); // initialize two product classes: Builder b1 = new ConcreteBuilder1 (); Builder b2 = new ConcreteBuilder2 (); // create product A ctor. construct (b1); // get final Product p1 = b1.GetResult (); p1.Show (); // create Product B ctor. construct (b2); // get the final Product p2 = b2.GetResult (); p2.Show (); Console. read ();}

Ii. prototype mode

Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

In prototype mode, another custom object is created from an object without any details.

In general, cloning is the best way to keep the initialization information unchanged. This not only hides the details of object creation, but also greatly improves the performance without re-initializing the object, instead, it dynamically obtains the running state of the object.

// Abstract Prototype class abstract class Prototype {private string id; // Constructor

Public Prototype (string id) {this. id = id;} // attribute public string Id {get {return id;} public abstract Prototype Clone ();} // Prototype 1 class ConcretePrototype1: prototype {public ConcretePrototype1 (string id): base (id) {}// create a superficial copy of the current object public override Prototype Clone () {return (Prototype) this. memberwiseClone () ;}// you can also use the ICloneable interface provided by NET to replace the class ConcretePrototype2: ICloneable {
Private string id; // Constructor
        public ConcretePrototype2 (string id)        {            this.id = id;        }
        public string Id 
       { 
get { return id; } 
       }
 
        public Object Clone()        {            return (Object)this.MemberwiseClone();        }    }
// Client code static void Main (string [] args) {// create p1 ConcretePrototype1 p1 = new ConcretePrototype1 ("I"); // copy it to c1 ConcretePrototype1 c1 = (ConcretePrototype1) p1.Clone (); Console. writeLine ("Cloned: {0}", c1.Id); ConcretePrototype2 p2 = new ConcretePrototype2 ("II"); ConcretePrototype2 c2 = (ConcretePrototype2) p2.Clone (); Console. writeLine ("Cloned: {0}", c2.Id); // Wait for user Console. read ();}

MemberwiseClone (): If the field is of the value type, perform a one-on-one copy of the field. If the field is of the reference type, copy the referenced object without copying the referenced object; therefore, the original object and its counterparts reference the same object.

Deep replication: points the variables of the referenced object to the new object that has been copied, instead of the original referenced object. If deep replication is required, you need to write a program in the replication method to convert any form of data to a value type and then copy it again.

Iii. Singleton Mode

Ensure that a class has only one instance and provides a global access point to it.

All classes have constructor methods. If no constructor is encoded, the system generates an empty constructor by default. If an explicit constructor is used, the default constructor fails, if you change the modifier of the constructor to private, the external program cannot instantiate the constructor with new.

Advantage: Let the class itself copy and maintain its unique instance. This class ensures that no other instance can be created, and provides a method to access the instance (the unique instance can strictly control how and when the user accesses it ).

// Singleton class Singleton {private static Singleton instance; private static readonly object syncRoot = new object (); // modify the constructor, so that the outside world cannot use new to create an instance private Singleton () {} // create an instance public static Singleton GetInstance () {// double lock, first determine whether the instance exists, if (instance = null) {// if no lock exists, the thread lock will be applied to prevent other threads from re-creating lock (syncRoot) when the previous thread is not finished) {if (instance = null) {// initialize instance = new Singleton () ;}} return instance ;}}

// Client code static void Main (string [] args) {// use this method to initialize the instance
            Singleton s1 = Singleton.GetInstance();
// Because s1 has already created an instance, s2 will not create a new instance again
            Singleton s2 = Singleton.GetInstance();            if (s1 == s2)            {                Console.WriteLine("Objects are the same instance");            }            Console.Read();        }

PS: lock ensures that when one thread is located in the Code critical section, the other thread does not enter the critical section. If other threads attempt to enter the locked code, it waits until the object is released.

Iv. Derivative

Static initialization: c # provides a "static initialization" method with the public Language Runtime library. This method does not require developers to explicitly write thread security code, it solves the problem of being insecure in a multi-threaded environment.

Hungry Chinese Singleton class: static Initialization is to instantiate itself when it is loaded. Generally enough

Lazy Singleton class: It is instantiated only when it is referenced for the first time.

// Add the sealed modifier to prevent derivation, the Derivation may add the instance public sealed class Singleton {// create the instance private static readonly Singleton instance = new Singleton (); private Singleton () when any member of the class is referenced for the first time () {} public static Singleton GetInstance () {return instance ;}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.