- Single case
- A single case is a design pattern
- Ensure that a class has at most one instance and is easy to access
- Single example implementation
- Privatization construction Method
- Built-in static instances
- Provides an interface for external use to obtain instances
-
1 usingSystem;2 3 namespaceSingletonpatterndemo4 {5 //Singleton-ensures that a class has a maximum of one unique object at the same time during the program's run, and that accessing the object is more convenient6 Public classPlayer7 {8 //properties of the player role9 Public stringname;Ten Public intLevel ; One Public intHP; A Public intmaxhp; - - //Public Property the - //3. Provide an interface to get the instance - Public StaticPlayer getinstance () - { + if(NULL==_instance) - { +_instance =NewPlayer (); A } at return_instance; - } - - //2. We need to provide a static instance within the class - Private StaticPlayer _instance; - in - //1. Privatization of construction methods-do not let the outside world arbitrarily create objects to PrivatePlayer () + { - the } * } $ Public classBagPanax Notoginseng { - Public voidUSEHP () the { +Player p =player.getinstance (); AP.HP + =Ten; the //ensure that the player's HP does not exceed the maximum value +P.HP = p.hp > p.maxhp?p.maxhp:p.hp; - } $ } $ class Program - { - Static voidMain (string[] args) the { -Player p =player.getinstance ();WuyiP.name ="Li"; theP.level =1; -P.HP =2; WuP.MAXHP = -; - AboutBag B =NewBag (); $ B.USEHP (); - - Console.WriteLine (P.HP); - A //The object that gets is still the object above, and indeed in the process of running the program, only one role enters the role +Player P2 =player.getinstance (); the Console.WriteLine (p2.name); - } $ } the}
"Learning Notes" C # single case