Design pattern learning notes (1)

xiaoxiao2021-03-06  102

Foreword has seen the design mode, some understand, some didn't understand, some understand, I have forgotten, some are not known when writing procedures. In short, now learn from the beginning And start making notes, so that this is prison. It is also aware of the design model to be close to the design pattern later. The classic "design model" is ready to buy a total of 23 design patterns. Here I have studied five kinds. After strict research, the example is C #, but for C , Java, Delphi should be Applicable. Welcome everyone to discuss me!

Directory 1.singleton2.strategy3.Decorator4.composite5.State

1.Singleton Description: The guarantee class has only one example. Example: Using System; Class Singleton {Private Static Singleton Singleton = NULL; Public Static Singleton Instance () {if (null == Singleton) Singleton = New Singleton (); Return Singleton;

PRIVATE SINGLETON () {}}

Class application {public static void main () {singleton s1 = singleleton.instance (); // singleton s2 = new singleleton (); // error: constructor is not accessible SINGETON S2 = Singleton.instance (); if (S1. Equals (S2)) // Reference equal console.writeline ("instances are identical");}}

/ * The following is the program output result: instances area Identical * /

2.Strategy Description: Use the interface implementation method indepresses, the customer program has no coupling relationship with a specific algorithm. Example: Using System;

Namespace Strategy1 {///

/// Summary Description for class. /// interface statulegy {bool isprime (int N);}

Class Miller: Strategy {public Bool isprime (int N) {bool result = false; // Test N is used by the Miller method, the result is true, then update the result value console.writeline ("Using Miller's Algorithm); Return Result;} }

Class Fermat: Strategy {public Bool IsPrime (int N) {bool result = false; // Test n if the FERMAT method is used to test the number, fruit, then update the result value console.writeline ("Using Fermat's Algorithm"); Return Result;} }

Class Mersenne: Strategy {public bool isprime (int N) {bool result = false; // Using the Mersenne method to test N is the number, fruit, then update the result value console.writeline ("Using Mersenne's Algorithm); Return Result;} } Class primality {priva {private statule;

Public primality (strategy s) {strategy = s;} public bool test (int N) {return strategy.isprime (n);}}

Class class {[stathread] static void main (string [] args) {console.write ("Number to be tsted:"); string infut = console.readline (); int n = int32.parse (input); console. Write ("Desired Algorithm Performance: Lo, Medium, Hi?"); Input = Console.readLine (); char ch = char.parse (input); primality prime = null; switch (ch) {copy 'L': CASE 'L': prime = new primality (new miller ()); Break;

Case 'M': Case 'M': Prime = New Primality (New Fermat ()); Break;

Case 'h': Case 'h': prime = new primality (new mersenne ()); Break;}

IF (prime! = null) {bool result = prime.test (n);} else console.writeline ("Bad Choice!");

Console.readline ();

}

}

/ * The following is a test output result: Number to be tsted: 1 de, Medium, Hi? M useing fermat's algorithm * /

3. Decorator Description: Flexible extension of functionality through subclass implementation. Example: Using System;

Namespace Decortation {///

/// Summary description for class. ///

Class FileTransfer {Public Virtual Void Download (String Url, Byte [] Data, INT Size {// Download File} Public Virtual Void Upload (String Url, Byte [] Data, INT Size {// Upload File}}

class Decorator: FileTransfer {private FileTransfer ft = new FileTransfer (); private bool IsAccessAllowed (string url) {bool result = true; // URL access authorization to decide whether to request return result;} private void LogAccess (string url) {/ / Write the URL, Time, User Identity, and the like to the database console.writeline ("Logging Access to {0}", URL);

Public Override Void Download (String Url, Byte [] Data, INT Size {if (! isaccessallowed (URL)) Return; Ft.Download (URL, DATA, SIZE); Logaccess (URL);

Public override void upload (string url, byte [] data, int size) {if (! isaccessallowed (URL)) Return; Ft.upload (URL, DATA, SIZE); logaccess (URL);}}

Class class {public static void main () {Console.write ("Enter URL TO Access:"); string url = console.readline (); console.write ("Enable Logging and access check?"); string input = console .Readline (); char ch = char.parse (input); bool decoration = (CH == 'y' || CH == 'y'); FileTransfer ft = null; if (! Decoration) ft = new fileTransfer ); Else ft = new decorator (); byte [] buf = new byte [1024]; ft.download (URL, BUF, 1024);}}

}

4.Composite Description: Use the interface to access all objects (this is common). Example: C # example: Using system; using system.collections; interface shape {void draw ();} class line: shape {private double x1, y1, x2, y2; public line (Double X1, Double Y1, Double X2, Double) Y2) {this.x1 = x1; this.y1 = Y1; this.x2 = x2; excitation void draw () {// From (x1, y1) to (x2, y2) draw a draw CONSOLE.WRITELINE ("Drawing a line");}} Class Circle: Shape {Private Double X, Y, R; Public Circle (Double X, Double Y, Double Radius) {this.x = x; THIS.Y = Y; this.R = r;} public void draw () {// Sahail, R is a radius, a radius ("Drawing a circle");}} Class Drawing: shape { private ArrayList shapes; public Drawing () {shapes = new ArrayList ();} public void Add (Shape s) {shapes.Add (s);} public void Draw () {IEnumerator enumerator = shapes.GetEnumerator (); while ( Enumerator.Movenext () (shape) enumerator.current) .draw ();}} Class Application {public static void main () {shape [] array = new shape [3]; array [0] = new line 0, 0, 10, 12); array [1] = new circle (2, 3, 5.5); Drawing DWG = New Drawing (); dwg.add (New Line (3, 4, 3, 5)); dwg.add (New Circle (5, 6, 7.7)); array [2] = dwg; // Draw all Graphics, Note: Access all objects for FOR (int i = 0; i <3; i) array [i] .draw ();}} / * The following is the program output result: Drawing a line Drawing a circle Drawing a line Drawing a circle * / 5.State Description: Automatically changing its behavior when the internal status changes.

Example: This instance is relatively long, I briefly explained that this is an example of an automatic vending machine, and the customer can throw a coin of 5, 10, 25, and the value of the goods 25. Whenever the customer is investigating the amount of money, if it is 25, it will be sold. State is an abstract class, which depends 5, 10, 15, 20, 25 yuan and classes (that is, all possible money and), because they are inherited from State, they all have a state. Type static member state as a status of the status (you can imagine it into a global variable), each class receives a coin invested 5, 10, 25-dimensional coins, the corresponding method is public Virtual Void Add Nickel (VendingMachine VM) {} public Virtual Void Adddime (VendingMachine VM) {} Public Virtual Void Addquarter (VendingMachine VM) {虽, although the method of each class is different, such as 5 yuan of class, after receiving 10 yuan, STATE is transition It is 15 yuan to push it in this class. Take a closer look, this is a very interesting example. But tell the truth, so that the implementation is really too tired, maybe you can reduce the burden on programmers in other applications, but I haven't found it (some words tell me). In addition, if there is 100 states, there are 10 kinds of paths, is it inherited by each state (100 × 10)? What Coding is not too tired, and the code should not be too long, hey, when the programmer is not easy ... Using system;

Abstract Class State

{

Public Virtual Void Add Nickel (VendingMachine VM) {}

Public Virtual Void AddDime (VendingMachine VM) {}

Public Virtual Void Addquarter (VendingMachine VM) {}

Protected Virtual Void ChangeState (VendingMachine VM, State S)

{

VM.ChangeState (s);

}

}

Class VendingMachine

{

PRIVATE STATE;

Public vendingmachine ()

{

Console.writeline ("The Vending Machine Is Now Online: Product Costs 25c");

State = start.instance ();

}

Public Void ChangeState (State To)

{

State = TO;

}

Public void vend ()

{

// send beverage

Console.WriteLine ("Dispensing Product ... Thank you!");

}

Public void add nickel ()

{

State.adDnickel (this);

}

Public void adddime ()

{

State.adddime (this);

}

Public void addquarter ()

{

State.addquarter (this);

}

}

Class Start: State

{

Private static state statness = new start ();

Private start ()

{

}

Public static state instance () {

// Singleton logic

Console.writeline ("CRedit: 0C");

Return State;

}

Public Override Void Add Nickel (VendingMachine VM)

{

ChangeState (VM, Five.instance ());

}

Public Override Void Adddime (VendingMachine VM)

{

ChangeState (VM, Ten.instance ());

}

Public Override Void Addquarter (VendingMachine VM)

{

vm.vend ();

}

}

Class Five: State

{

Private static state state = new five ();

Private file ()

{

}

Public Static State Instance ()

{

// Singleton logic

Console.writeline ("CREDIT: 5C");

Return State;

}

Public Override Void Add Nickel (VendingMachine VM)

{

ChangeState (VM, Ten.instance ());

}

Public Override Void Adddime (VendingMachine VM)

{

ChangeState (VM, Fifteen.instance ());

}

Public Override Void Addquarter (VendingMachine VM)

{

vm.vend ();

ChangeState (VM, Start.instance ()); // no change returned :-)

}

}

Class Ten: State

{

Private static state state = new ten ();

private ten ()

{

}

Public Static State Instance ()

{

// Singleton logic

Console.writeline ("CREDIT: 10C");

Return State;

}

Public Override Void Add Nickel (VendingMachine VM)

{

ChangeState (VM, Fifteen.instance ());

}

Public Override Void Adddime (VendingMachine VM)

{

ChangeState (VM, TWENTY.INSTANCE ());

}

Public Override Void Addquarter (VendingMachine VM)

{

vm.vend ();

ChangeState (VM, Start.instance ()); // no change returned :-)

}

}

Class Fifteen: State

{

Private static state statness = new fifteen ();

Private fifteen ()

{

}

Public Static State Instance ()

{

// Singleton logic

Console.writeLine ("CREDIT: 15C");

Return State;

}

Public Override Void Add Nickel (VendingMachine VM)

{

ChangeState (VM, TWENTY.INSTANCE ());

}

Public Override Void Adddime (VendingMachine VM) {

vm.vend ();

ChangeState (VM, Start.instance ());

}

Public Override Void Addquarter (VendingMachine VM)

{

vm.vend ();

ChangeState (VM, Start.instance ()); // no change returned :-)

}

}

Class TWENTY: STATE

{

Private static state statness = new twenty ();

Private twenty ()

{

}

Public Static State Instance ()

{

// Singleton logic

Console.writeLine ("CREDIT: 20C");

Return State;

}

Public Override Void Add Nickel (VendingMachine VM)

{

vm.vend ();

ChangeState (VM, Start.instance ());

}

Public Override Void Adddime (VendingMachine VM)

{

vm.vend ();

ChangeState (VM, Start.instance ());

}

Public Override Void Addquarter (VendingMachine VM)

{

vm.vend ();

ChangeState (VM, Start.instance ()); // no change returned :-)

}

}

Class Application

{

Public static void main ()

{

INT COIN = 0;

String infut = null;

Vendingmachine vm = new vendingmachine ();

While (True)

{

Console.Write ("INSERT A COIN (5, 10, 25):");

INPUT = console.readline ();

COIN = Int32.Parse (Input);

Switch (coin)

{

Case 5:

VM.Addnickel ();

Break;

Case 10:

vm.adddime ();

Break;

Case 25:

vm.addquarter ();

Break;

DEFAULT:

Break;

}

}

}

}

/ * The following is a certain runtime output result:

The Vending Machine is now Online: Product Costs 25c

Credit: 0C

INSERT A Coin <5, 10, 25>: 5

Credit: 5C

INSERT a Coin <5, 10, 25>: 10

Credit: 15c

INSERT A Coin <5, 10, 25>: 5

Credit: 20C

INSERT A Coin <5, 10, 25>: 5

Dispensing Product ... Thank you!

* /

转载请注明原文地址:https://www.9cbs.com/read-122905.html

New Post(0)