Design pattern learning notes (2)

xiaoxiao2021-03-06  95

table of Contents

6.Prototype

7.BUILDER

8.Astract Factory

9.Factory Method

6.Prototype Description: Realize the deep copy of the object (or shallow copy). Deep copy refers to the entity copy of the object, and the shallow copy only returns the reference to the object. The Icloneable interface is provided in C #, which only has a clone () method (this is similar to Java), and we use it to implement the Prototype mode. Shallow copy implementation: The MEMBERWISECLONE () method is provided under System Namespace, and it can be called in Clone (). Realization of deep copy: Manual implementation, look at the example below. Example: // ---- Shallow Copy -------- Using System; Namespace Prototype_Shallow {// Because we have such an interface in the FCL So we don't define new prototype Public Class Concreteprototype1: Icloneable {private int m_ID; public int ID {get {return this.m_ID;}} public ConcretePrototype1 (int id) {this.m_ID = id;} public object Clone () {return this.MemberwiseClone ();}} public class ConcretePrototype2 : ICloneable {private int m_ID; public int ID {get {return this.m_ID;}} public ConcretePrototype2 (int id) {this.m_ID = id;} public object Clone () {return this.MemberwiseClone ();}}} // The following is the call section concreteprototype1 p1 = new conttePrototyPe1 (1); concreteprototype1 c1 = (concreteprototype1) p1.clone ();

// ---- Deep copy ---------- Namespace prototype_deep {using system.collections; public class concreteprototype: iCloneable {private int m_id; public int id {get {returnim_id;} private ArrayList m_arrayList = new ArrayList (); public ConcretePrototype (int id) {this.m_ID = id; this.m_arrayList.Add ( "FirstObject"); this.m_arrayList.Add ( "secondObject"); // ...} public object Clone () {ConcretePrototype c = new ConcretePrototype (this.ID); c.m_arrayList = new ArrayList (); c.m_arrayList.Add ( "FirstObject"); c.m_arrayList.Add ( "secondObject"); return c ;} public ConcretePrototype DeepClone () {return (ConcretePrototype) this.Clone ();}}} // The following is a calling part ConcretePrototype p = new ConcretePrototype (1); ConcretePrototype c = p.DeepClone (); this.richTextBox1.AppendText (P.TOST Ring () ":" p.id.toTString () "this.richtextbox1.appendtext (c.Tostring () ": " C.Id.toTString () " / n " ); C.m_arrayList [0] = "change"; for (int i = 0; i <= 1; i ) {this.richtextbox1.appendtext (c.m_arraylist [i] .tostring ());} this.richtextbox1 .Appendtext ("/ n"); for (int i = 0; i <= 1; i ) {this.richtextbox1.appendtext (p.m_arraylist [i] .tostring ());}

7.Builder Description: Builder is very well understood, it is to achieve complex objects into several simple objects, as if the production car is, it is assembled from each part. I think if each child does not depend on each other, using this mode, very good, can be flexible to assemble new complex classes. Example: using System; namespace Builder_Me {using System.Collections; // specifies an abstract interface for creating parts of a Product object // create an object of a specified portion of an interface public interface Builder {void BuildPartA (); void BuildPartB (. .); Product GetResult ();} // constructs and assembles parts of the product by impementing the Builder interface // defines and keeps track of the representation it creates // provides an interface for retrieving the product public class ConcreteBuilder1: Builder.. {private Product m_Product; public void BuildPartA () {this.m_Product = new Product (); this.m_Product.AddParts ( "1", "PartA");} public void BuildPartB () {this.m_Product.AddParts ( "2 "," PartB ");} public Product GetResult () {return this.m_Product;}} public class ConcreteBuilder2: Builder {private Product m_Product; public void BuildPartA () {// otherwise you must call this method can not instantiate objects this .m_Product = new product (); this.m_p Roduct.Addparts ("3", "part1");

public void BuildPartB () {this.m_Product.AddParts ( "4", "Part2");} public Product GetResult () {return this.m_Product;}} // construct an object using the Builder interface public class Director {public. void Construct (Builder builder) {// not change the order builder.BuildPartA (); builder.BuildPartB ();}} // represents the complex object under construction.ConcreteBuilder builds // the product's internal representation and defines the process by which it's // assemblyd. // incrudes classes That Define the constituent parts, incruding interfaces for // assembly. // To create a complex object This object we expressed in a HashTable. public class Product {Hashtable m_Parts = new Hashtable (); public void AddParts (string partKey, string partValue) {this.m_Parts.Add (partKey, partValue);} public string ShowSelfParts () {string strResult = string.Empty; int i = 1; FOREACH (String stramp in this.m_parts.values) {strresult = "part" i.tostring () ": / t" strtmp "/ n"; i ;}}} customer end the following code fragment: Director director = new Director (); Builder builder1 = new ConcreteBuilder1 (); Builder builder2 = new ConcreteBuilder2 (); director.Construct (builder1); Product p1 = builder1.GetResult (); this.richTextBox1.AppendText (P1.Showselfparts ()); Director.Construct (Builder2); Product P2 = Builder2.getResult (); this.richtextbox1.appendtext (p2.showselfparts ());

8.Astract Factory Description: Provides an interface to create a series of associated or interdependent objects without having to specify their specific classes. Example: using System; namespace AbstractFactory_Maze {using Maze; public interface AbstractFactory {MazeClass MakeMaze (); Wall MakeWall (); Room MakeRoom (int n); Door MakeDoor (Room oneRoom, Room otherRoom);} public class MazeFactory: AbstractFactory {public MazeClass MakeMaze () {return new MazeClass ();} public Wall MakeWall () {return new Wall ();} public Room MakeRoom (int n) {return new Room (n);} public Door MakeDoor (Room oneRoom, Room otherRoom ) {return new Door (oneRoom, otherRoom);}} // this is a client public class MazeGame {public MazeClass MazeCreate (AbstractFactory factory) {MazeClass aMaze = factory.MakeMaze (); Room r1 = factory.MakeRoom (1); Room r2 = factory.makeroom (2); door adoor = factory.makedoor (R1, R2); Amaze.Addroom (R1); Amaze.Addroom (R2); r1.setside (Direction.North, Factory.makewall ()) R1.setside (direction.east, adoor); R1.SETSIDE (Direction.South, Factor y.makewall ()); r1.setside (direction.west, factory.makewall ()); r2.setside (Direction.North, Factory.makewall ()); r2.setside (direction.east, factory.makewall () ); R2.setside (Direction.South, Factory.makewall ()); R2.Setside (Direction.West, Adoor); Return Amaze;}}} Namespace Maze {Using System.collections;

Public class mapsite {public virtual void enter () {}}

Public Enum Direction {North, South, EAST, West}

Public class room: mapsite {public string print () {string result = ""; for (int i = 0; i <= 3; i ) {switch (i) {case (int) Direction.east: {Result = "EAST IS:" THIS.GETSIDE (Direction.east) "/ T"; Break;} case (int) Direction.North: {Result = "north is:" this.getside (direction (direction) "/ t"; break;} case (int) Direction.South: {result = "South IS:" this.getside (direction.South) "/ t"; Break;} case (int) Direction.west : {RESULT = "West is:" this.getside (direction.west) "/ t"; break;}}} return result;} public room (int N) {this.m_roomnumber = n;} public mapsite Getside (Direction Dir) {Return this.m_sides [(int) DIR];

public void SetSide (Direction dir, MapSite mapSite) {this.m_sides [(int) dir] = mapSite;} public override void Enter () {} private MapSite [] m_sides = new MapSite [4]; int m_roomNumber;} public class Wall: MapSite {public Wall () {} public override void Enter () {}} public class Door: MapSite {public Door (Room oneRoom, Room otherRoom) {} public override void Enter () {} public Room oneRoom {get { return this.m_oneRoom;} set {this.m_oneRoom = value;}} private Room m_oneRoom; public Room otherRoom {get {return this.m_otherRoom;} set {this.m_otherRoom = value;}} private Room m_otherRoom; private bool m_isOpen; Public Bool Isopen {Get {Return this.m_isopen;} set {this.m_isopen = value;}}} public class mazeclass}} public class mazeclass {} public string print () {String Result = ""; for (int i = 0; i <= this.m_maze.count-1; i ) {result = this.roomnumber (i) .prin T () "/ n";}} public void addroom (room room) {m_maze.add (room);}

public Room RoomNumber (int roomNumber) {return (Room) this.m_Maze [roomNumber];} private ArrayList m_Maze = new ArrayList ();}} private void Form1_Load (object sender, System.EventArgs e) {AbstractFactory factory = new MazeFactory ( ); MazeGame Game = new mazegame (); majclass amaze = game.mazecreate (factory); this.richtextbox1.appendtext (amaze.print ());} The following is the output result: North Is: maze.wall South IS: maze. Wall East Is: Maze.Wall North Is: Maze.wall South Is: Maze.Wall East Is: Maze.wall West Is: Maze.door

9.Factory Method Description: The purpose of the factory method is clear that it is to define an interface to create an object, but he does not directly create an object, but he is created by his subclasses, so that the responsibility of the creation of the object is delayed. In the subclass of the interface, what type of object created is determined by subclats, and the time to create an object is determined by the interface. Example: Using system; using system.collections; // This namespace is some of the environments of running instances include Maze, Door, etc. Namespace CommonObject {// All maze components. The base class is used to display the current component. Information PUBLIC CLASS MAPSITE {PUBLIC Virtual String Enter () {Return String.empty;}} // Wall is one of the components that make up the maze, here is a very general wall (no bomb) public class wall: Mapsite {public override String Enter () {Return "this is a wall."; PUBLIC WALL () {}} // The door is also one of the components of the maze, which is also a very ordinary door (not magic) public class door: Mapsite {Public override string enter () {return "this is a door."; Door (room roomfrom, room room) {this.m_room1 = roomfrom; this.m_room2 = roomto;} // Let's have the opportunity to enter another house from the door, will get // another house reference Public Room OthersideFrom Room RoomFrom) {if (this.m_room1 == RoomFrom) Return this.m_room2; else returnim_room 1;} // This is some private variable private room m_room1; private room m_room2; // Describes the state of the door defaults all new doors are off private bool m_isopen = false; // Provide a public access to accessor public accessor PUBLIC Bool isopen {set {this.m_isopen = value;} get {return this.m_isopen;}}

} // Room is the basic unit of the labyrinth public class room: mapsite {// enumeration Type indicates the house of the house PUBLIC ENUM SIDES {north = 0, EAST, South, West} public override string enter () {return "this IS a room. ";} // Constructor, in order to distinguish between our rooms, add a lablic room (int roomnumber) {this.m_roomnumber = roomnumber;

// Set the face of the house, the house has four faces because we don't know the specific type of each face //, so we use the MapSite type. Public void setside (Side, Mapsite Sidemap) {this.m_side [(int) Side] = SIDEMAP;

// Get the specified surface, and we don't know which one is //, so we return to the structure using MapSite PUBLIC MAPSITE GETSIDE (SIDES SIDE) {Return this.m_side [(int) Side];}

// Some private member room number protected int m_roomnumber; // The house has 4 protected const Int m_sides = 4; // Stores unknown types (walls or gates) protected mapsite [] m_side = with a 1-dimensional MapSite array New mapsite [m_sides];

}

// House with bombs Public class bombedroom: room {public bombedroom (int roomnumber): base (roomnumber) {}}

// House with maze public class enchantedroom: room {public enchantedroom (int Roomnumber, Spell Spell): Base (roomnumber) {}}

// This is a special wall - Public Class Bombedwall with bomb: Wall {} // This is a Magic door public class enchantedDoor: door {public enchantedDoor (roomboomfrom, room room): base (roomfrom, Roomto) {}}

// This is our maze public class Maze {private ArrayList m_Rooms = new ArrayList (); public Room RoomNumber (int roomNumber) {return (Room) this.m_Rooms [roomNumber];} public void AddRoom (Room room) {this .m_rooms.add (room);}}

@ Magic class public class Spell {}} The next is to realize a factory method: using System; using System.Collections; namespace FactoryMethod_Example {// Add MazeContext using CommonObject; // public class implements some factories Creator method class MazeGame { / / To return to the object private maze m_maze = null; // An accessor is used to get Maze public maze {get {if (this.m_maze == null) this.m_maze = cretemaze (); returnim_maze; }}} // Constructor Public Mazegame () {} // The following is some factory methods to create a maze of each component for each component () {return new maze ();} public virtual room makeroom (Int ID) {Return New Room (ID); PUBLIC Virtual Wall Makewall () {Return New Wall ();} Public Virtual Door Makedoor (Room Room1, Room Room2) {Return New Door (Room1, Room2);} / / Create a maze public maze createmaze () {maze = makemaze (); // Creating a door and room Room Room1 = makeroom (1); room room2 = makeroom (2); door thedoor = Makedoor (Room1, Room2); // Add the room to Maze.Addroom (Room1) in the labyrinth; maze.addroom (room2); // Set the ROOM1 surface Room1.setside (room.sides.North, makewall ()); room1.sets.east , THEDOOR); ROOM1.SETSIDE (room.sides.South, makewall ()); room1.setside (room.Sides.west, makewall ()); // Set the surface Room2.setside of Room2 (room.sides.North, Makewall ()); Room2.Setside (room.sides.east, makewall ()); room2.setside (room.sides.South, makewall ());

Room2.setside (room.sides.west, thedoor); return maze;}}

// Create a bomb maze public class bombedmazegame: MazeGame {public bombedmazegame () {} public override wall make makewall () {return new bombedwall ();

Public override room makeroom (int N) {return new bombedroom (n);}}

// Create a maze public class enchazegame: MazeGame {

Private Spell M_SPell;

Public EnchantedMAZEGAME (Spell Spell) {this.m_spell = SPELL; PUBLIC OVERRIDE DOOR MAKEDOOR (ROOM R1, ROOM R2) {RETURN New EnchantedDoor (R1, R2);}

Public Override Room Makeroom (INT N) {Return New EnchantedRoom (n, this.m_spell);}

}

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

New Post(0)