Design Pattern Series 1 (simple factory vs factory method)

Source: Internet
Author: User

1. Simple factory Introduction

Background: In our common programming, we often use new to instantiate an object. In this case, this class is completely dependent on this object. In terms of professional terms, it is highly coupled. When the demand changes, we have to modify the source code, making it difficult to maintain the entire system! However, an important principle of object-oriented (OO) (encapsulation changes) can solve such a problem. To encapsulate changes, you must find the changed code, then, encapsulate the changed code in a class. Such an idea leads to a simple factory model.

Definition: simple factory mode is also called static factory mode. As its name suggests, it is a static class used to instantiate object classes.

2. Simple factory instance

 

/// <Summary> // animal abstract class /// </Summary> public abstract class animal {public abstract void eat (); public abstract void call ();} public class Cat: Animal {public override void eat () {console. writeline ("fish");} public override void call () {console. writeline ("Miao... ") ;}} public class Dog: Animal {public override void eat () {console. writeline ("shit");} public override void call () {console. writeline ("Wang... ") ;}//< summary> /// simple factory class /// </Summary> public class animalsimplefactory {public static animal createanimal (string type) {animal = NULL; Switch (type) {Case "cat": Animal = new CAT (); break; Case "dog": Animal = new dog (); break; default: break;} return animal ;}}

Client call method:

    static void Main(string[] args)        {            Animal animal = AnimalSimpleFactory.CreateAnimal("dog");            animal.Eat();            animal.Call();            Console.ReadLine();        }

Resolution: The createanimal method in animalsimplefactory is responsible for the production of specific animal, which reduces the coupling between objects. However, if we want to add a new type of animal, we still need to modify the code in the factory class (new case statement Judgment), which also violates the OCP principle, and also causes the implementation logic in the factory class to be too complex, this is also the disadvantage of the simple factory model!

3. Factory method mode

Background: In order to solve the problem that the simple factory mode still cannot fully meet the OCP principle, we think about the factory method mode!

Implementation Method: A simple factory has only one (for a project or an independent module) factory class, while the implementation of the factory method mode delays the creation of a specific object to a subclass, at this time, the factory class is no longer responsible for the creation of all objects, but only sends a password to transfer the process of creating the object to its subclass. In this way, the logic of the factory class does not need to be modified when it is expanded, therefore, OCP is fully satisfied!

4. Factory method mode instance

 

/// <Summary> // animal abstract class /// </Summary> public abstract class animal {public abstract void eat (); public abstract void call ();} public class Cat: Animal {public override void eat () {console. writeline ("fish");} public override void call () {console. writeline ("Miao... ") ;}} public class Dog: Animal {public override void eat () {console. writeline ("shit");} public override void call () {console. writeline ("Wang... ");}} /// <summary> /// abstract factory class /// </Summary> public abstract class animalcreater {// factory method public abstract animal createanimal ();} public class catcreater: animalcreater {public override animal createanimal () {return new CAT () ;}} public class dogcreater: animalcreater {public override animal createanimal () {return new dog ();}}

Client call method:

     static void Main(string[] args)        {            AnimalCreater catCreater = new CatCreater();            Animal cat = catCreater.CreateAnimal();            cat.Eat();            cat.Call();            AnimalCreater dogCreater = new DogCreater();            Animal dog = dogCreater.CreateAnimal();            dog.Eat();            dog.Call();            Console.ReadLine();        }

Resolution: If you want to add new animals, you can use polymorphism. No changes are required for the code in the abstract factory class and the specific object creation class; we only need to define a new animal and animal creation class!

5. Comparison between simple factory mode and factory method mode

From the introduction of the two models above, we can see that the factory method model is designed to overcome the disadvantages of the simple factory model (mainly to meet the OCP. However, the factory method model must be better than the simple factory model? The author's answer is not necessarily!

1. Structure Complexity
From this perspective, it is obvious that the simple factory model should be dominant. The simple factory mode requires only one factory class, while the factory class of the factory method mode increases with the number of product classes, which will undoubtedly increase the number of classes and increase the complexity of the structure.

2. Code complexity
There is a conflict between Code complexity and Structure Complexity. Since the simple factory mode is relatively simple in structure, it must be more complex in code than the factory method mode. The factory class in the simple factory mode needs to add many methods (or Code) as the product class increases, while the factory method mode only completes a single task for each specific factory class, and the code is concise.

3. Client programming difficulty
Although the factory method mode satisfies the OCP, the factory class needs to be instantiated in the client encoding. In the simple factory mode, a static method does not need to be instantiated on the client, which is undoubtedly an attractive advantage.

 

Note: The two have their own merits. The benevolent sees benevolence, and the wise sees wisdom!

 

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.