The difference and combination of simple factory model and strategy mode

Source: Internet
Author: User

Objective:

The simple Factory mode and strategy mode is the majority of programmers, in the study of design patterns in contact with the earliest, or in the work practice is also used in a relatively more than two design patterns.

One is the creation type, the other is the behavioral type, however two different types of patterns, in some places also have a trace of similarities, at the same time in a certain scenario combined with, can play a particularly good effect.

Problem:

I think the simple factory model is very similar to the strategy model. How is it similar? All three business subclasses inherit the abstract parent class by passing in parameters to the container class (The factory class of Factory mode, the content class of the policy mode), and selecting the corresponding class for the behavior operation.

In fact, the UML diagram does not look much different from the appearance, but the essence is very big difference.

Simple Factory mode

As mentioned above, the simple Factory mode is the creation mode, the creation mode as the name implies, that is, when creating the object, encountered a bottleneck will be selected design mode. So what's the use of it?

The essence of the simple factory pattern is that a factory class dynamically determines which product classes (these product classes inherit from a parent class or interface) should be created and returned based on the parameters passed in.

So that means:

1, there is a known product class

2, you can not exactly know which product class to compile

3. Need to decide which product class to create at run time

4, the product category is not many

It is clear that there is a high level of flexibility in creating objects, but the factory class can only create product classes that may be used, and if the new product class is modified, the factory class is violated, which violates the open and closed principle.

Policy mode

The strategy pattern is the behavioral pattern, which defines a series of algorithms, encapsulates each algorithm, and allows them to be replaced with each other. The policy pattern makes the algorithm independent of the customers who use it.

In a piece of code, using logical Control (if-else,swich-case) to determine the algorithm, the algorithm has similar methods and functions, you can choose the policy mode.

So that means:

1, there are several conditional statements in a method, there are many behavior processes in the conditional statement code block.

2, the algorithm can be encapsulated into the policy class

2, the algorithm arbitrary switch

3, algorithm and client isolation

In this way, the corresponding algorithm is configured at run time by selecting the corresponding policy class, which is passed as a parameter to the content class.

Summary of differences

From the above description, it concludes that both are configured by passing in parameters at run time, while the simple Factory mode chooses to create the desired object, while the policy pattern is to configure the desired behavior algorithm. One is object creation and the other is the substitution of the behavioral algorithm.

Combine

Here's a code for a policy pattern.

usingSystem;usingSystem.Net.Configuration;namespacestrategywithfactory{classProgram {Static voidMain (string[] args) {Strategy Strategycontent=NULL; //pseudo code. Get input algorithm typeEstrategy InputType =Requestinput (); if(InputType = =estrategy.a) {NewContent (NewStrategya ()).            Contentinterface (); }            Else if(InputType = =estrategy.b) {NewContent (Newstrategyb ()).            Contentinterface (); }            Else if(InputType = =estrategy.c) {NewContent (NewSTRATEGYC ()).            Contentinterface (); }        }    }    //algorithm abstract class    Abstract classStrategy { Public Abstract voidAlfoeirhminterface (); }    //a algorithm class    classStrategya:strategy { Public Override voidAlfoeirhminterface () {Console.WriteLine ("The Strategya"); }    }    //B Algorithm Class    classStrategyb:strategy { Public Override voidAlfoeirhminterface () {Console.WriteLine ("The strategyb"); }    }    //B Algorithm Class    classStrategyc:strategy { Public Override voidAlfoeirhminterface () {Console.WriteLine ("The strategyc"); }    }    //Context Class    classContent {Private ReadOnlystrategy _strategy;  PublicContent (Strategy strategy) {_strategy=strategy; }         Public voidContentinterface () {_strategy.        Alfoeirhminterface (); }    }    //Algorithm Enumeration    enumEstrategy {A=1, B=2, C=3    }}

The above code is the prototype of the strategy mode, if the main function is the client, then each additional algorithm, the client will have to modify at once, add an else if, causing unnecessary trouble. Well, now, first we know the existing ABC three algorithms, but we are not sure which algorithm to use at runtime, and in order to isolate the client and business logic code, we can transfer the client's creation algorithm class business logic to the Cotent class, and add a method to create the algorithm factory.

usingSystem;namespacestrategywithfactory{classProgram {Static voidMain (string[] args) {            //pseudo code. Get input algorithm typeEstrategy InputType =Requestinput (); NewContent (InputType).        Contentinterface (); }    }    //Context Class    classContent {Private ReadOnlystrategy _strategy;  PublicContent (Estrategy estrategy) {_strategy=createfactory (estrategy); }         PublicStrategy Createfactory (Estrategy estrategy) {strategy Strategy=NULL; Switch(estrategy) { CaseEstrategy.a:strategy=NewStrategya ();  Break;  CaseEstrategy.b:strategy=NewStrategyb ();  Break;  CaseEstrategy.c:strategy=NewSTRATEGYC ();  Break; }            returnstrategy; }         Public voidContentinterface () {_strategy.        Alfoeirhminterface (); }    }}

Then the combination of the strategy and the simple factory is implemented.

The difference and combination of simple factory model and strategy mode

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.