Design Mode note (5)-factory method mode (creation type)

Source: Internet
Author: User
Document directory
  • Gof Definition
  • Motivation
  • Complete code
  • Key points of the factory Method Design Pattern
Gof Definition

Define an excuse for creating an object so that the subclass decides which class to instantiate. The factory method delays the instantiation of a class to the subclass.

Motivation

In software systems, the creation of "an object" is often faced. due to changes in requirements, this object is often faced with drastic changes, but it has a relatively stable excuse.

Suppose there is a scenario like this: an automobile and an automobile testing framework. The automobile testing framework is responsible for testing the automobile. We usually want to write it like this.

public class Car{    public void Startup() { }    public void Run(){ }    public void Turn(Direction direction) { }    public void Stop() { }}
Testing Framework
class CarTestFramework{    public void BuildTestContext()    {        Car car = new Car();        //do something    }    public void DoTest()    {        Car car = new Car();        //do something    }    public void GetTestData()    {        Car car = new Car();        //do something    }}

Each method in the above test framework class cartestframework may instantiate the car class. The above code is a car class that is directly instantiated. In this way, there is a strong dependency between the framework and automobile. In reality, our testing framework class cannot only test one type of car. Therefore, when the type of the car to be tested changes, the testing framework class also needs to change, this is certainly not what we want. Now let's abstract the car class.

public abstract class AbstractCar{    public abstract void Startup();    public abstract void Run();    public abstract void Turn(Direction direction);    public abstract void Stop();}

After an abstract car class is created, the test framework class will change accordingly. We may quickly Replace the car with the abstractcar feature, as shown below:

class CarTestFramework{    public void BuildTestContext()    {        AbstractCar car = new AbstractCar();        //do something    }        //....}

It is easy to see that the above Code is actually incorrect, and the abstract class cannot be instantiated. In this case, another method may be used to instantiate the subclass using an abstract class.

class CarTestFramework{    public void BuildTestContext()    {        AbstractCar car=new Car();        //do something    }    //......}

However, there is still a problem in doing so. We still use a specific car class during instantiation, which still produces a dependency on the car. Therefore, a factory class is required to create objects. The following describes how to create a factory class carfactory.

public class CarFactory{    public AbstractCar CreateCar()    {        return new Car();    }}

The code of the test framework class is as follows:

Class cartestframework {public void buildtestcontext (carfactory) {abstractcar car1 = carfactory. createcar (); abstractcar car2 = carfactory. createcar (); abstractcar car3 = carfactory. createcar ();//... no matter how many methods need to be created using the factory class }//........}

Call as follows in the client program

public class App{    public void Main()    {        CarTestFramework carTestFramework = new CarTestFramework();        carTestFramework.BuildTestContext(new CarFactory());        //....     }}

The code above shows that the parameters passed in to the test framework class are a factory-class object, and the factory-class method createcar is a car class directly returned, in this way, the coupling relationship is moved to the createcar of the factory class, resulting in a strong dependency. Assume that there is a hongqicar <to be tested, you need to change the createcar method as follows:

public class HongqiCar:AbstractCar{    public override void Startup() { }    public override void Run() { }    public override void Turn(Direction direction) { }    public override void Stop() { }}

Changed factory class

public class CarFactory{    public AbstractCar CreateCar()    {        return new HongqiCar();    }}

This design is obviously not good. Since the strong dependency occurs in the factory class, the factory class can also be abstracted.

public abstract class AbstractCarFactory{    public abstract AbstractCar CreateCar();}

As mentioned above, if hongqicar needs to be tested, a factory class that generates hongqicar will be created. This class inherits the abstract factory class.

public class HongqiCarFactory : AbstractCarFactory{    public override AbstractCar CreateCar()    {        return new HongqiCar();    }}

Now the customer program can be changed to this

public class App{    public void Main()    {        CarTestFramework carTestFramework = new CarTestFramework();        carTestFramework.BuildTestContext(new HongqiCarFactory());        //....     }}

In this way, if you have new requirements, such as adding auticar for testing, you only need to do the following steps:

1. Add the auticar class to inherit the abstractcar class.

public class AudiCar : AbstractCar{    public override void Startup() { }    public override void Run() { }    public override void Turn(Direction direction) { }    public override void Stop() { }}

2. Add the factory class of audicar to inherit the abstractcarfactory class.

public class AudiCarFactory : AbstractCarFactory{    public override AbstractCar CreateCar()    {        return new AudiCar();    }}

3. Make minor changes to the customer program.

Public class app {public void main () {cartestframework = new cartestframework (); cartestframework. buildtestcontext (New hongqicarfactory (); // Add a line of code to cartestframework. buildtestcontext (New audicarfactory ());//....}}
Complete code

Abstractcar. CS

/// <Summary> /// abstract automobile class /// </Summary> public abstract class abstractcar {public abstract void startup (); public abstract void run (); public abstract void turn (direction); public abstract void stop ();}

Abstractcarfactory. CS

/// <Summary> /// abstract factory class /// </Summary> public abstract class abstractcarfactory {public abstract abstractcar createcar ();}
CarTestFramework.cs
/// <Summary> /// test framework class /// </Summary> public class cartestframework {public void buildtestcontext (abstractcarfactory) {abstractcar car = abstractcarfactory. createcar ();} public void dotest (abstractcarfactory) {// do something} public void gettestdata (abstractcarfactory) {// do something }}

App. CS

/// <Summary> /// customer class /// </Summary> public class app {public void main () {cartestframework = new cartestframework (); cartestframework. buildtestcontext (New hongqicarfactory ());//....}}

The above is the basic code. If you need a car to be tested, you only need to add two concrete classes to inherit the abstract car class and abstract factory class, then, you can make slight modifications to the customer program, and the customer program can also add configuration files through reflection without any modifications. In this way, the OCP principle is well met, and demand changes can be expanded as long as new classes are available.

Key points of the factory Method Design Pattern
  • The factory method mode is used to isolate the coupling between the users of class objects and specific types. In the face of a changing type, tight coupling may lead to software vulnerabilities.
  • The factory method mode uses object-oriented methods to delay the work of the specific object to be created to the subclass, so as to implement an extension (rather than change) policy, this tightly coupled relationship is better solved.
  • The factory method mode solves the change of "single object", the abstract factory mode solves the change of "series object", and the builder mode solves the change of "Object part.

Return to the beginning (INDEX)

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.