Design Pattern: simple pattern and strategy Pattern

Source: Internet
Author: User

Recently, I learned many similarities between simple factory models and policy models. They all use polymorphism to select different sub-classes, which is difficult to distinguish. So I made a summary.

Simple factory models are used for example, algorithms for addition, subtraction, multiplication, division, fruit for apple, pear, bananas, and stationery. The common characteristics of these examples are that they are specific, limited in quantity, and do not involve complex algorithms, the simple factory mode only solves the problem of object creation. The factory class encapsulates all the selection processes. If the object needs to be increased, reduced, or changed, it is necessary to change the factory, so that the amount of code rewriting increases, and in the operation process, the customer needs to specify a parameter for the factory, the factory selects the derived class to be instantiated according to the parameter. In the simple factory mode, the customer needs to know the abstract base class and factory class. The factory class is used to generate objects and the abstract base class interface is used to complete the work. Its core is "simple mode is used to encapsulate all objects ".

The following is an example of a simple factory model:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace simple factory mode {class Program {static void Main (string [] args) {Operation; operator = OperationFactory. createOperate ("+"); forward. numberA = 1; Numeric. numberB = 4; double result = random. getResult (); Console. writeLine ("result:" + result);} public class Operation // abstract class {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 ;}} public virtual double GetResult () {double result = 0; return result ;}} class OperationAdd: operation // base class: Addition {public override double GetResult () {double result = 0; result = NumberA + NumberB; return result;} Class OperationSub: Operation // subtraction {public override double GetResult () {double result = 0; result = NumberA-NumberB; return result;} class OperationMul: operation // multiplication {public override double GetResult () {double result = 0; result = NumberA * NumberB; return result ;}} class OperationDiv: operation // division {public override double GetResult () {double result = 0; if (NumberB = 0) thro W new Exception ("the divisor cannot be 0. "); Result = NumberA/NumberB; return result ;}// factory class public class OperationFactory {public static Operation createOperate (string operate) {Operation = null; switch (operate) {case "+": condition = new OperationAdd (); break; case "-": condition = new OperationSub (); break; case "*": break = new OperationMul (); break; case "/": break = new OperationDiv (); break;} return break ;}}}}
Due to frequent changes in the form of product objects, the use of the simple factory mode will lead to code re-writing, while the policy mode avoids this. It defines the algorithm family and encapsulates them separately, so that they can replace each other, and the algorithm changes will not affect the customer's use of the algorithm, which is suitable for a large number of complex operations. The difference between the algorithm and the simple factory model is that it does not have a factory class, instead, the factory class code is written to the client. The client includes code with various functions. When using the Policy mode, you must first create a class and pass the class objects, the following Context is used to call different algorithms through this object. It gives the factory of the selected object to the user who uses this mode. its core is that the rule mode is used to encapsulate algorithms. However, in practice, we find that it can be used to encapsulate almost any type of rules, as long as different business rules need to be applied at different times during the analysis process, you can consider the possibility of using the Policy mode to handle such changes.

The following is an example of a policy pattern:

Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. threading. tasks; using System. windows. forms; namespace ce {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {cbxType. items. add ("normal"); cbxType. items. add ("discount"); cbxType. items. add ("rebate");} private void btnOk_Click (object sender, EventArgs e) {CashSuper csuper = CashFactory. createCashAccept (cbxType. selectedItem. toString ();} // cash receipt abstract class CashSuper {public abstract double acceptCash (double money);} // class CashNormal, a subclass of normal billing: cashSuper {public override double acceptCash (double money) {return money ;}// class CashRebate: CashSuper {private double moneyRebate = 1d; public CashRebate (string moneyRebate) {this. moneyRebate = double. parse (moneyRebate);} public override double acceptCash (double money) {return money * moneyRebate;} // class CashReturn: CashSuper {private double moneyCondition = 0.0d; private double moneyReturn = 0.0d; public CashReturn (string moneyCondition, string moneyReturn) {this. moneyCondition = double. parse (moneyCondition); this. moneyReturn = double. parse (moneyReturn);} public override double acceptCash (double money) {double result = money; if (money> = moneyCondition) result = money-Math. floor (money/moneyCondition) * moneyReturn; return result ;}// class CashFactory {public static CashSuper CreateCashAccept (string type) // cash receiving factory {CashSuper cs = null; switch (type) {case "normal charge": cs = new CashNormal (); break; case "300 to 100 ": cashReturn cr1 = new CashReturn ("300", "100"); cs = cr1; break; case "0.8 off": CashRebate cr2 = new CashRebate "); cs = cr2; break;} return cs;} class CashContext {private CashSuper cs; // declare a CashSuper object; public CashContext (CashSuper csuper) // Through the constructor, enter a specific billing policy; {this. cs = csuper;} public double GetResult (double money) {return cs. acceptCash (money); // calculate the result based on different charging policies; }}// client form program double total = 0.0d; private void bntOk_Click (object sender, EventArgs e) {CashContext cc = null; switch (cbxType. selectedItem. toString () {case "normal charge": cc = new CashContext (new CashNormal (); break; case "300 to 100 ": cc = new CashContext (new CashReturn ("300", "100"); break; case "off ": cc = new CashContext (new CashRebate ("0.8"); break;} CashSuper csuper = CashFactory. createCashAccept (cbxType. selectedItem. toString (); double totalPrices = 0d; // Through polymorphism, you can get the result of totalPrices = csuper. acceptCash (Convert. toDouble (txtPrice. text) * Convert. toDouble (txtNum. text); total = total + totalPrices; lbxList. items. add ("unit price:" + txtPrice. text + "Quantity:" + txtNum. text + "" + cbxType. selectedItem + "Total:" + totalPrices. toString (); lblResult. text = total. toString ();}}}
You should have some understanding of these two models through these two sections of code and my description. I hope you can point out more!

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.