Overview
In software systems, the creation of "an object" is often faced. due to changes in requirements, the specific implementation of this object is often subject to drastic changes, however, it has relatively stable interfaces. How to deal with this change? A new packaging mechanism is provided to isolate the changes of "this variable object", so as to keep the "other objects dependent on this object" in the system from changing as required? This is the Factory Method mode.
Intention
Defines an interface for users to create objects, so that the subclass determines which class to instantiate. Factory Method delays the instantiation of a class to its subclass.
Structure chart
Role description:
Abstract Factory role: it is the core of the factory method model and has nothing to do with applications. Any factory class of the object created in the mode must implement this interface.
Concrete Creator: this is a specific factory class that implements Abstract Factory interfaces. It contains the logic closely related to applications and is called by applications to create product objects. There are two such roles: BulbCreator and TubeCreator.
Abstract Product role: the super type of the object created in the factory method mode, that is, the common parent class of the Product object or the common interfaces. In, this role is Light.
Specific Product role: this role implements the interface defined by the abstract Product role. A specific product is created in a specific factory, which is usually one-to-one.
Examples in life
The factory method defines an interface for creating objects, but the subclass determines which class to instantiate. Injection Molding demonstrates this mode. Plastic toys manufacturers process plastic powder and inject the plastic into the desired shape of the mold. The type of toys (cars, people, etc.) is determined by the mold.
Example
If you go to McDonald's for a hamburger, the hamburger production process is a factory method. The example is shown below:
Code Design
Create Hamburger. cs First:
Html # viewSource "commandName =" viewSource "highlighterId =" highlighter_679260 "> view sourceprint?
1 |
public abstract class Hamburger |
3 |
public abstract string BuyHamburger(); |
Create CheeseBurger. cs again:
View sourceprint?
1 |
public class CheeseBurger : Hamburger |
3 |
public override string BuyHamburger() |
5 |
return "What you want is cheese burger" ; |
Create RoastedChickenBurger. cs again:
View sourceprint