Singleton design pattern: Instantiate only one Class object!
1 Public class Person2 {3 //1: First define a static variable4 //2: Privatize the constructor of this class5 //3: Define a static method that assigns the class object to this static variable6 //4: Use class in other classes. Method name to invoke the object7 Public StaticPerson p1;8 PrivatePerson ()9 {Ten } One Public StaticPerson Get () A { - if(P1 = =NULL) - { theP1 =NewPerson (); - } - returnP1; - } + } - class Program + { A Static voidMain (string[] args) at { -person P1 =person.get (); - } -}
Design Pattern II: Simple Factory
Defines a factory class that can return instances of different classes depending on the parameters, and the instances that are created usually have a common parent class.
1: Define a parent class
Public Abstract class person { publicabstractvoid Say (); Public Person () { } }
2: Definition of two sub-classes
1 classFather:person2 {3 Public Override voidSay ()4 {5Console.WriteLine ("I'm a dad .");6 }7 }8 classSon:person9 {Ten Public Override voidSay () One { AConsole.WriteLine ("I'm a son ."); - } -}
3: Define Simple factory class
1 Public Abstract classTool2 {3 Public StaticPerson St (stringtype)4 {5Person p1=NULL;6 Switch(type)7 {8 Case"dad":9p1=NewFather ();Ten Break; One Case "son": AP1 =NewSon (); - Break; - the - - } - returnP1; + - } +}
Design Patterns: Singleton and Simple Factory