Design Patterns (simple factory model), designpatterns

Source: Internet
Author: User

Design Patterns (simple factory model), designpatterns

The article is very long and wonderful. If you are a beginner, please watch it patiently. (Please detour !)

Simple factory mode:

1. Create Mode

2. Overview of simple factory models

3. Structure and Implementation of the simple factory Model

4. Simple factory application example

5. Create and use objects

6. Simplified Simple factory Model

7. Advantages and disadvantages of the simple factory model and the applicable environment

 

1. Creational Pattern ):

Follow the object creation process creation mode to abstract the class instantiation process, which can separate the creation of objects in the software module from the use of objects, this mode hides the creation details of class instances. It describes how to separate object creation and use, so that users do not need to care about object creation details when using objects, this reduces the Coupling Degree of the system and makes the design scheme easier to modify and expand. (Creation Mode focus: 1. what do I create? 2. who created it? 3. When to create ?)

 

 

 

 

 

 

 

Mode name Definition Learning Difficulty Usage Frequency

Simple factory Mode

(Simple Factory Pattern)

Defines a factory class. It can return instances of different classes according to different parameters. The created instances usually share the same parent class. ★★☆☆☆ ★★★☆☆

Factory method mode

(Factory Method Pattern)

Define an interface for creating objects, but let the subclass decide which class to instantiate. The factory method mode delays the instantiation of a class to its subclass. ★★☆☆☆ ★★★★★

Abstract Factory Model

(Abstract Factory Pattern)

Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes. ★★★★☆ ★★★★★

Builder Mode

(Builder Pattern)

Separates the construction of a complex object from its representation, so that different representations can be created during the same construction process. ★★★★☆ ★★☆☆☆

Prototype

(Prototype Pattern)

Use the prototype instance to specify the type of the object to be created, and copy the prototype to create a new object. ★★★☆☆ ★★★☆☆

Singleton Mode

 

(Singleton Pattern)

Make sure that a class has only one instance and provides a global access point to access this unique instance. ★☆☆☆☆ ★★★★☆

2. Overview of simple factory models:

Basic implementation process of simple factory Mode

Specific product categories: encapsulate the code of various product objects to be created into specific product categories

Abstract product class: abstracts and extracts common code of a specific product class and encapsulates it in an abstract product class.

Factory class: provides a factory class for creating various products, and provides a factory method for creating products in the factory class. This method can create different product Objects Based on different input parameters.

 

Client: you only need to call the factory method of the factory class and input the corresponding parameters to obtain a product object.

 1 if(arg.Equals("A")) 2 { 3       return new ConcreteProductA(); 4 } 5 else if(arg.Equals("B")) 6 { 7       return new ConcreteProductB(); 8 } 9 else10 {11       .......12 }

Simple factory model definition:

 

(1)Simple Factory Pattern: defines a Factory class, which can return instances of different classes according to different parameters. The created instances usually have a common parent class.

(2) In Factory mode, the Method used to create an instance is usually the static Method, which is also called the Static Factory Method mode.

 

Key Point: If you need anything, you only need to pass in a correct parameter to obtain the desired object without having to know its creation details.

★Structure of simple factory Mode

3.Structure and implementation of simple factory Mode

Structure of simple factory Mode

The simple factory model contains the following three roles:

Factory (Factory role)

Product (Abstract Product role)

 

ConcreteProduct (specific product role)

Implementation of simple factory Mode

Typical abstract Product Code:

 

1 abstract class Product 2 {3 // public Business Method of all Product classes 4 public void MethodSame () 5 {6 // public method implementation 7} 8 9 // declare abstract Business Method 10 public abstract void MethodDiff (); 11}

 

Typical Product Code:

1 class ConcreteProductA: Product2 {3 // Business Method 4 public override void MethodDiff () 5 {6 // business method implementation 7} 8}

 

Typical Factory Code:

 

Class Factory {// static Factory method public static Product GetProduct (string arg) {Product product = null; if (arg. equals ("A") {product = new ConcreteProductA (); // initialize the set product} else if (arg. equals ("B") {product = new ConcreteProductB (); // initialization settings product} return product ;}}

 

Typical client code:

1 class Program 2 {3 static void Main (string [] args) 4 {5 Product product; 6 product = Factory. getProduct ("A"); // create A product object through the factory class 7 product. methodSame (); 8 product. methodDiff (); 9} 10}

4. Simple factory application example

Instance description:

A software company needs to develop a chart Library Based on the C # language. This chart library can provide various charts with different appearances for the application system, such as HistogramChart and PieChart), line chart, etc. The design personnel of the chart library of the software company hope to provide a flexible and easy-to-use chart library for application system developers. Different types of charts can be obtained by setting different parameters, in addition, you can easily expand the chart library to add new types of charts in the future.

 

The chart library is designed in simple factory mode.

Instance code

(1) Chart: the abstract Chart interface acts as an abstract product class.

(2) HistogramChart: A column chart class that acts as a specific product class

(3) PieChart: Pie Chart class, acting as a specific product class

(4) LineChart: line chart class, acting as a specific product class

(5) ChartFactory: a chart factory class that acts as a factory class.

(6) Program: client test class

Reference Code: (DesignPatterm \ SimpleFactory)

 

 

Introduce the configuration file: App. config:

Using System. Configuration ;...... // Read the configuration file string chartStr = ConfigurationManager. etettings ["chartType"];... <? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <appSettings> <add key = "chartType" value = "histogram"/> </appSettings> </configuration> ...... Chart chart; chart = ChartFactory. GetChart (chartStr); // create a product using the static factory method ......

5. Create and use objects

C # How to create objects in the language

Use the new Keyword to directly create an object

Create an object using the reflection mechanism

Create an object using the clone method

Create an object through the factory class

Use the new Keyword to create an object:

Class Login {private UserDAO udao; public Login () {udao = new OracleUserDAO (); // create an object // if the above line of code is changed to SQL ServerUserDAO, the source code must be modified, // violates the open/closed principle} public void Execute () {// other code udao. findUserById (); // use object // other code }}

Instance analysis

Introduce the factory class UserDAOFactory:



 

 

Instance analysis

Introduce factory class UserDAOFactory

If the constructor of a sub-class of UserDAO changes or you need to add or remove different sub-classes, as long as the code of UserDAOFactory is maintained, Login is not affected.

If the interface of UserDAO changes, such as adding or removing methods or changing the method name, you only need to modify Login without affecting UserDAOFactory.

Other benefits of separating object creation and use

The data and code used to instantiate a class are everywhere in multiple classes. You can move the created knowledge to a factory class to solve the problem of code duplication and creation spread.

The constructor name is the same as the class name, from the list of constructors and parameters, it is difficult to understand the differences between Products Constructed by different constructors. The object creation process is encapsulated in the factory class, A series of factory methods with different names can be provided. Each factory method corresponds to a constructor, and the client can create objects in a more readable and understandable way.

When do I not need a factory?

No need to assign a factory class to every class in the system

If a class is very simple, and there are no too many changes, its construction process is also very simple. In this case, you do not need to provide a factory class for it, just instantiate it before use.

Otherwise, the factory may flood, increasing the complexity of the system.

Example: string class

When do I not need a factory?

No need to assign a factory class to every class in the system

If a class is very simple, and there are no too many changes, its construction process is also very simple. In this case, you do not need to provide a factory class for it, just instantiate it before use.

Otherwise, the factory may flood, increasing the complexity of the system.

 

Example: string class

6. Simplified Simple factory Model

Merge abstract product classes and factory classes, and move static factory methods to abstract product classes.

 

7. Advantages and disadvantages of the simple factory model and the applicable environment

Advantages:

Separated object creation and usage

The client does not need to know the class name of the created product class, but only needs to know the parameter corresponding to the specific product class.

 

By introducing a configuration file, you can replace and add new product classes without modifying any client code, which improves system flexibility to a certain extent.

Disadvantages:

The factory class has centralized the creation logic of all products, and has too many responsibilities. Once it fails to work properly, the entire system will be affected.

Increase the number of classes in the system (new factory classes are introduced), increasing the complexity and difficulty of understanding the system.

System expansion is difficult. Once a new product is added, the factory logic has to be modified.

Due to the use of the static factory method, the factory role cannot form a hierarchy based on inheritance, and the factory class cannot be well expanded.

Applicable environment:

The factory class is responsible for creating a small number of objects, because the number of created objects is small, it will not cause the business logic in the factory method to be too complex

 

The client only knows the parameters passed into the factory class and does not care about how to create objects.

 

At this point, my article is coming to an end. Thank you for reading my Blog. More exciting content will be available in the future. Please pay attention to it. Thank you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.