Design pattern learning notes (3)

xiaoxiao2021-03-06  83

9.Factory Method

10.SIMPLE FACTORY

11.Adapter

12.Proxy

Sorry! About Factory This type of mode, the order here is unreasonable, you should read 10.SIMPLE FACTORY first, then 9.Factory Method, the last 8.Abstract factory, this is the shallow depth, it is better to understand, in fact, it is from the product Start abstraction, then go to the factory, then go to a factory abstraction process. I think this model is in business-level development.

9.Factory Method

Note: Estimated the example of the previous section, everyone didn't understand, here, listen to this mode, please look carefully.

Note: This sentence I don't quite understand "This makes the factory method model allow the system to introduce new products without modifying specific factory roles, making it superiority of simple factory models." I don't know what to refer to it here. Abstract factory class is also an instance factory, but I think, whether it is necessary to modify it when I introduce new products, I don't know if I understand it?

Example:

Design mode C # description - factory method mode

Factory method mode is a class creation mode, called virtual construct sub-model or polymorphic factory model. Its intention is to define a factory interface that creates a product object, delays the actual creation work into the subclass.

Disadvantages of simple factory model:

Because the factory class has a logic of all products, if it is not possible to work, it will have a big impact on the system. If you add new products, you must modify the source code of the factory role.

The advantages of factory method model:

In the factory method mode, the core factory class is no longer responsible for all products creation, but will give the created work to the subclass. This core class is a role of an abstract factory, only responsible for giving interfaces that must be implemented by specific factory subclasses without contacting which product class instantiated details. This allows the factory method model to allow the system to introduce new products without modifying the specific plant role, making it superiority of simple factory models.

The specific implementation of this mode is discussed below:

Abstract Factory Role (CREATOR): Started with the core of factory method model, which provides an interface that creating an object's factory class.

ConcentecReetecreator: Responsible for the creation of specific product objects to implement the interface specified by Creator.

Abstract Product Role (Product): The super-type of the object to be created in the factory method mode, which specifies the interface that the product should have.

ConcreteProduct: Realize the interface specified by Product.

The sample code is as follows:

Creator:

Public Interface Creator

{

Product factory (); // factory method

}

Concretecreator1:

Class Concretecreator1: Creator

{

Public product factory () // factory method

{

Return New ConcreteProduct1 ();

}

}

Concretecreator2:

Class Concretecreator2: Creator

{

Public product factory () // factory method

{

Return New ConcreteProduct2 ();

}

}

Product:

Public Interface Product

{

}

ConcreteProduct1:

Class ConcreteProduct1: Product

{

Public contRoduct1 ()

{

Console.writeline ("Creat ConcreteProduct1);

}

ConcreteProduct2:

Class ConcreteProduct2: Product

{

Public contRoduct2 ()

{

Console.writeline ("Creat ConcreteProduct2);

}

}

Client:

Class Client

{

Private static creator1, creator2;

Private statino

[Stathread]

Static void

Main

(String [] ARGS)

{

Creator1 = new concretecreator1 ();

PRODUCT1 = CREATOR1.FACTORY ();

Creator2 = new concretecreator2 ();

Product2 = creator2.factory ();

}

}

10.SIMPLE FACTORY

Note: Simple factory model is not mentioned in the "Design Mode" (English version) book, but many other models have been mentioned, I don't know if this mode is relatively intuitive. This mode is very well understood, which is to define a unified interface, then derpt some classes from this interface, and then create an instance of these derived classes with a factory class. This is not the same as the previous Factory Method, and Factory Method defers actually created work to the subclass.

The disadvantage of this mode: Since the factory class has a logic of all product creation, if it is not working properly, it will have a large impact on the system. If you add new products, you must modify the source code of the factory role.

Example:

The following example is found online, writing very well, very easy to understand.

In fact, the design model is not a deep theory. Personally think that it is not like some people say "did not write 100,000 code, don't talk about design mode", as long as learning and practice is fully capable. ??????

Simple factory model is a class creation mode and is called static factory method mode. It is an example of which product class is created by a factory class based on incoming parameters. It is generally related to three roles (as shown below):

Factory: The role is the core of the factory method model, which contains the close-related business logic. The factory class creates a product object under the direct call of the client, which is often implemented by a specific class.

Abstract Product Role (Product): A class that serves this role is the parent class of an object created by the factory method mode, or the interface they share. Generally implemented by an interface or abstract class.

Specific product role (ProductA, ProductB): Any pair created by factory method mode

The like is all instances of this role, implemented by specific classes.

Simple factory model advantages and disadvantages:

The core of the mode is a factory class. This class is responsible for the creation of the product, and the client can exempt the responsibility of product creation, which implements the division of responsibility. However, because the factory class has concentrated on all product creation logic, if it does not work properly, it will have a big impact on the system. If you add new products, you must modify the source code of the factory role.

Taking the garden-planted fruits to discuss the specific implementation of this model:

Fruit Fruit Interface, Some common features of fruits

Apple Apple derived from Fruit interface

Strawberry Strawberry Class Delivery from Fruit Interface

Fruitgardener gardener is responsible for strawberry and apple creation.

When the Client wants to create fruit (Apple or Strawberry Object), call the gardener's Factory method creation: UML map is as follows: The code is as follows:

FRUIT.CS

Namespace Simple_Factory

{

Public Interface Fruit, INTERFAIT

{

// Growth

Void growth ();

//reward

Void Harvest ();

// plant

Void Plant ();

}

}

Apple.cs

Namespace Simple_Factory

{

Public Class Apple: Fruit

{

Public apple ()

{

}

#Region Fruit member

Public void greow ()

{

Console.writeline ("Apple Is Growing ...";

}

Public void harvest ()

{

Console.WriteLine ("Apple Is Harvesting .......");

}

Public void plant ()

{

Console.writeLine ("Apple Is Planting ...");

}

#ndregion

}

}

Strawberry.cs

Namespace Simple_Factory

{

Public Class Strawberry: fruit

{

Public strawberry ()

{

}

#Region Fruit member

Public void greow ()

{

Console.writeline ("strawberry is growing ...");

}

Public void harvest ()

{

Console.writeline ("strawberry is harvesting ...");

}

Public void plant ()

{

Console.writeline ("strawberry is planting ...");

}

#ndregion

}

}

Fruitgardener.cs

Namespace Simple_Factory

{

Public Class Fruitgardener

{

// static factory method

Public Static Fruit Factory (String Which)

{

IF (Which.equals ("apple"))

{

Return new apple ();

}

Else IF (Which.equals ("strawberry"))

{

Return new strawberry ();

}

Else

{

Return NULL;

}

}

}

}

Client.cs

Using system;

Namespace Simple_Factory

{

Class Client

{

[Stathread]

Static void

Main

(String [] ARGS)

{

Fruit AFRUIT = Fruitgardner.Factory ("apple"); // Creat Apple

Afruit.grow ();

Afruit.harvest ();

Afruit.plant ();

Afruit = fruitgardner.Factory ("strawberry"); // Creat Strawberry

Afruit.grow ();

Afruit.harvest ();

Afruit.plant ();

}

}

}

The output is as follows:

Apple is groing .......

Apple is harvesting .......

Apple is planting .......

Strawberry is groing .......

Strawberry is harvesting .......

Strawberry is planting .......

11.Adapter

Description: Two different forms of adapter mode and object adapter mode, belonging to a better understanding, specifically look at the following code.

The adapter mode converts a class interface into another interface that the client is expected, so that two classes that cannot be worked together by the interface do not match together can work together. ??

The class's adapter mode converts the API of the adapted class into the target class API.

Example:

The role of the mode is as follows:

Target Role: This is the interface that is expected. Note that the class's adapter mode is discussed here, so the target cannot be a class.

ADAPTEE Role: Exported interfaces that require adaptation.

Adapter Role: Convert the source interface into a target interface.

Target;

Public Interface Target

{

Void sampleOperation1 ();

Void sampleOperation2 (); // Source class is not included

} // end interface definition target

Adaptee;

Public Class Adaptee

{

Public void sampleOperation1 ()

{

}

} // End class definition adaptee

Adapter;

Public Class Adapter: Adaptee, Target

{

Public void sampleOperation2 ()

{

}

} // End class definition adapter

Effect of class adapter mode:

Use a specific class to adapt the source to the target, so that if the source and source subclasses use this type of adaptation, the shape is not connected.

Since the adapter class is a subclass of the source, some of the methods can be replaced in the adapter class.

Similar to the adapter mode of the class, the object's adapter mode converts the API of the adapted class into the API of the target class, different from the adapter mode of the class, the adapter mode of the object is not connected to the Adaptee class with inheritance relationship, but use delegation Relationship, class diagram as follows:

Target;

Public Interface Target

{

Void sampleOperation1 ();

Void sampleOperation2 ();

} // end interface definition target

Adaptee;

Public Class Adaptee

{

Public void sampleOperation1 ()

{

}

} // End class definition adaptee

Adapter:

Public Class Adapter: Target

{

Private adaptee adaptee;

Public void adapter (Adaptee Adaptee)

{

THIS.Adaptee = adaptee;

}

Public void sampleOperation1 ()

{

Adaptee.sampleOperation1 ();

}

Public void sampleOperation2 ()

{

}

} // End class definition adapter

Object adapter mode effect: A adapter can fit multiple different sources to the same goal. That is, the same adapter can adapt the source class and its subclasses to the target interface.

Compared with the adapter of the class, it is not easy to want to replace the source class. If you have to replace the source class, you have to make a subclass of a source class, replace the method, and then adapt the subclass of the source class as a real source.

12.Proxy

Description: The agent mode is a mode of understanding. There are not many C # examples on the Internet. The following VB.NET is not very difficult, it should be easy to understand, so don't write it with C # rewritten .

When we need to use the objects, you can use a proxy mode (Proxy). For example, if you build an object takens to time and computer resources, proxy mode allows us to control this situation until we need to use the actual object. A agent (Proxy) typically contains the same method as the object to be used, once you start using this object, which will pass the agent (Proxy) to the actual object.

Some situations where proxy mode (proxy) can be used:

An object, such as a large image, is a long time to load.

A calculation result takes a long time can be completed, and the intermediate result needs to be displayed during its calculation.

An object that exists on a remote computer requires a long time to load this remote object over a network, especially in the peak period of network transmission.

A object only has limited access, proxy mode (Proxy) verifies user permissions

Proxy mode (Proxy) can also be used to distinguish a request and actual access of an object instance, for example: during initialization

Multiple objects may be created, but it is not all used immediately, and the proxy mode (proxy) can load the real object required.

This is a program that needs to load and display a large image. When the program starts, you must determine the image to display, but the actual image can only be displayed after full load! At this time we can use the proxy mode (Proxy).

This proxy mode (Proxy) can delay the load of the actual image until it receives a PAINT request. During the load period of the actual image, we can preload a relatively small, simple graphic by proxy mode (Proxy).

Example:

Simply illustrate this program, first create a picture proxy class, create an actual picture after 5 seconds, and create a proxy picture before this. When the user clicks the button, pass the image object in the image proxy class to the true picture class.

Public Class ImageProxy

Private done as boolean

Private TM as Timer

Public Sub New ()

DONE = FALSE

'Setting Timer Delay for 5 seconds

TM = New Timer (_

New TimerCallback (Addressof Tcallback, ME, 5000, 0)

End Sub

Public function isready () as boolean

Return Done

END FUNCTION

Public function getImage () as image

DIM IMG As IMAGER

'Display a pre-image until the actual image is loaded

IF isready then

IMG = new finalImage ()

Else

IMG = New QuickImage ()

END IF

Return Img.getimage

END FUNCTION

Public Sub Tcallback (Byval Obj As Object)

DONE = TRUE

TM.Dispose () End Sub

END CLASS

Define a simple interface:

Public Interface Imager

Function GetImage () as image

End interface

Implement the interface:

Pre-loaded images:

Public Class QuickImage

IMPLEMENTS IMERER

Public function getImage () as image_

Implements iMager.getimage

Return New Bitmap ("Box.gif")

END FUNCTION

END CLASS

Categories that load the actual image:

Public Class FinalImage

IMPLEMENTS IMERER

Public function getImage () as image_

Implements iMager.getimage

Return New Bitmap ("Flowrtree.jpg")

END FUNCTION

END CLASS

In a form of displaying an image, define an image agent (Proxy) instance, in loading the image button event, load the image: private imgproxy as imageproxy

Public Sub New ()

Mybase.new

FORM1 = ME

InitializeComponent

IMGPROXY = new imageProxy ()

End Sub

Protected Sub BTload_Click (Byval e as system.eventargs) Handles BTload.click

Pic.Image = imgproxy.getimage

End Sub

to sum up:

This is just a very simple example (example from "C # Design Mode"), you can have a preliminary understanding of the agent (Proxy) through this example! Adapter mode and proxy mode (Proxy) are constructed between the objects to construct a simple layer. However, the Adapter mode provides a different interface to the object, and proxy mode provides the same interface to the object.

?

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

New Post(0)