Simple Factory mode and factory method mode

Source: Internet
Author: User
One: Simple Factory mode

1, Concept

A simple factory model is a factory object that determines which product class instances are created. As the name implies, the factory is the production of things, there are raw materials (parameters), mold (object) can produce a lot of objects with the same function. 2,UML Chart

3, code example

    Class Program {static void Main (string[] args) {Operate oper; Create the Oper class of the operate class Oper = Operationfactoty.createoperate ("+"); Use simple factory to judge the strength of the object oper.  Numbera = 1; Assign a value of oper.
            Numberb = 2; Double result = oper.
            GetResult ();  Console.WriteLine (result); Show operation Result}}//Simple factory, by judging parameters, instantiate the corresponding object public class Operationfactoty {public static O
            Perate createoperate (string operate) {operate oper = null;
        Switch (operate) {} return oper;    }}//defines an operation base class that contains the GetResult virtual method public class Operate//defines an operation class {private Double numbera=0;    The number of private double numberb=0 before the operation; Number after operation public double numbera{} public double numberb{} public virtual Double GetResult      ()//The method of returning the result after operation {return result; Four inheritance classes that return the result}//Operation class, respectively, to implement the Add and subtractMultiplication four operations public class numberadd:operate//Add operation {public override double GetResult ()//Implement virtual method in base class
            {Double result = Numbera + Numberb;
        return result; }} public class Numbersub:operate//minus operation {public override double GetResult () {}} Publi C class Numbermul:operate//Multiply operation {public override double GetResult () {}} public class Numberdiv: Operate//Except operation {public override double GetResult () {}}

4, Summary

Simple Factory mode, I understand it as a mold, according to the external given raw materials, in addition to their own packaging good judgment, the production of different types of corresponding products, objects. Simple Factory mode usage Scenario: The factory class is responsible for creating fewer objects; The customer knows only the parameters of the incoming factory class, and does not care about how to create the object (logic); Simple factories can easily violate the principle of high cohesion and low coupling, so they are generally used only in very simple cases.

Two: Factory method mode

1, Concept

is to define a factory interface that creates a product object, so that subclasses decide which class to instantiate and defer the actual creation to subclasses.

2,UML Chart

3, code example

(1) Factory method Realization

    Class Program {static void Main (string[] args) {Ifactory factory = new Undergraduate   Factory (); Created by the interface new Lei Feng University students leifeng student = Factory.   Createleifeng (); Instantiate the student.
            Buyrice (); Student.
            Sweep (); Student.
        Wash (); }}//Lei Feng class, defines some functions class Leifeng {public void Sweep () {}//wipe table public void Wash () {}// Laundry public void Buyrice () {}//Buy Rice}//Learn Lei Feng's undergraduate class undergraduate:leifeng{}//community volunteer Clas
    S volunteer:leifeng{}//Lei Feng Factory interface ifactory//define an interface that implements the function of creating Lei Feng class {Leifeng Createleifeng ();
            } class undergraduatefactory:ifactory//Lei Feng University student Factory {public Leifeng Createleifeng () {
        return new undergraduate ();
            }} class volunteerfactory:ifactory//community volunteer Factory {public Leifeng Createleifeng () {
        return new volunteer ();
    }} 

    (2) Simple factory implementation

 class program {static void Main (string[] args) {Leifeng Studenta
            = Simplefactory.createleifeng ("Students studying Lei Feng");//Use simple factory to create and instance chemical Lei Feng's college students Studenta.buyrice ();
        Leifeng STUDENTB = Simplefactory.createleifeng ("community Volunteer");//Create an instantiated community volunteer with a simple factory studentb.buyrice (); }}//Lei Feng class, defines some functions class Leifeng {public void Sweep () {}//wipe table public void Wash () {}// Laundry public void Buyrice () {}//Buy Rice}//Simple factory class Simplefactory {public static Leifeng
            Createleifeng (String type) {Leifeng result = null; switch (type)//Determine the type of object to create {case "college student of Lei Feng": result = new Undergraduate
                    ();
                Break
                   Case "Community Volunteer": result = new Undergraduate ();
            Break
        } return result; }

    }

4, Summary

In the factory method model, the "factory" creates an object that has not yet been differentiated, in which there is no logical judgment compared to the simple factory model, the base class factory to implement the interface, the sub-factory to realize the judgment and can produce the corresponding function of the object.

Three: Comparison of simple factory and factory method models

1, simple Factory mode

Specifically defining a factory class is responsible for creating instances of other classes, the biggest benefit is that the factory class contains the necessary logic to dynamically instantiate the related class according to the conditions the customer needs

2, factory method mode

Create an interface for the object, let the subclass decide the object of the concrete instantiation, and move the simple internal logic judgment to the client code. The factory approach overcomes the drawbacks of simple factories violating the open-closed principle, while preserving the advantages of the encapsulation object creation process.



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.