Design Mode ------ factory method mode

Source: Internet
Author: User

The factory method mode defines an interface used to create objects so that the subclass decides which class to instantiate. The factory method delays the instantiation of a class to its subclass.

Role:

1. Abstract Factory (Creator) role:

Is the core of the factory method model and has nothing to do with applications. Any factory class that creates an object in the mode must implement this interface.


2. Specific Factory (ConcreteCreator) role:

This is a specific factory class that implements Abstract Factory interfaces. It contains the logic closely related to the application and is called by the application to create product objects.


3. Abstract Product role:

The super type of the object created in the factory method mode, that is, the common parent class of the product object or the interface of the product object.


4. Specific product (ConcreteProduct) roles:

This role implements the interface defined by the abstract Product role. A specific product is created in a specific factory, which is usually one-to-one.


Structure:


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + signature + m/Signature + signature + Wz/Signature/7O8aOsyrXA/buvuMO + signature + rP2vt/Signature + signature/Signature + rL6tcSjrLy01 + signature/Signature + tXf0ru3vaOsy/release + m/9sC0yrXA/release + jrLb41eK49r72st + 5/release + release/release + PHN0cm9uZz48YnI + export = "http://www.2cto.com/uploadfile/Collfiles/20140516/20140516093528138.jpg" alt = "\">

Simple factory type:


The factory class contains the necessary logical judgment, and the related class is dynamically instantiated Based on the Selection Conditions of the client. For the client, remove the dependencies with specific products. When adding other algorithms, you need to add the case branch condition in the factory class, which violates the "open-closed principle ".

Simple factory Mode Link


2. Factory method mode:



The factory method mode abstracts the simple factory mode and moves the internal logic judgment of the simple factory to the client. It has an abstract Factory class (which can be an abstract class and an interface). This class is no longer responsible for specific product production, but only for some specifications. The specific production work is completed by its subclass.


Factory method mode implementation:

Operation class:

Class Operation {private double _ numberA = 0; private double _ numberB = 0; public double NumberA {get {return _ numberA;} set {_ numberA = value ;}} public double NumberB {get {return _ numberB;} set {_ numberB = value ;}/// obtain the calculation result public virtual double GetResult () {double result = 0; return result ;}}

Addition class:

 class OperationAdd : Operation    {        public override double GetResult()        {            double result = 0;            result = NumberA + NumberB;            return result;        }    }

Subtraction class:

class OperationSub : Operation    {       ...    }

Multiplication class:

 class OperationMul : Operation    {        ...    }

Division class:

Class OperationDiv: Operation {public override double GetResult () {double result = 0; if (NumberB = 0) throw new Exception ("the divisor cannot be 0. "); Result = NumberA/NumberB; return result ;}}

According to the dependency inversion principle, the factory class is abstracted into an interface, which has a factory method for creating abstract products. All factories that produce specific classes must implement this interface.

Factory:

 interface IFactory    {        Operation CreateOperation();    }

Addition Factory:

// The factory class AddFactory responsible for producing "+": ifacloud {public Operation CreateOperation () {return new OperationAdd ();}}

Subtraction Factory:

// Factory class SubFactory responsible for producing "-": ifacloud {public Operation CreateOperation () {return new OperationSub ();}}

Multiplication Factory :...

Division Factory :...

Client:

Static void Main (string [] args) {IFactory operFactory = new AddFactory (); // when performing other operations, you only need to modify Operation operations = operFactory here. createOperation (); operation. numberA = 1; Numeric. numberB = 2; double result = random. getResult (); Console. writeLine (result); Console. read ();}

The "3" value is displayed in the console window ".


Analysis:

Core factory classes are no longer responsible for product creation and become an abstract factory role, so that the instantiation of a class is delayed to its subclass, this further abstracts the factory method model so that the system can introduce new products without modifying the specific factory role. When a new algorithm is added, you do not need to change the original factory class. You only need to add the operation class of this function and the corresponding production factory. This function is only available for expansion and disabled for modification, it makes up for the shortcomings of the simple factory, maintains the advantages of the encapsulated object creation process, and reduces the coupling between the customer program and the product object. The disadvantage of the factory method is that each time a product is added, classes of the product factory need to be added, and reflection technology can be improved.


Note: by writing a blog, I have deepened my understanding and accumulated knowledge. You are welcome to give us some advice and make progress together.


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.