Simple Factory mode and Factory method mode [Factory Pattern]

Source: Internet
Author: User
// Simple factory Mode
Public abstract class pizza
{}
Public class pizzaA: pizza
{}
Public class pizzaB: pizza
{}
// Currently, this pizza can serve many customers who need pizza Information
Public class simplePizzaFactory
{
Public pizza createPizza (string type)
{
Pizza p = null;
If (type = "")
{
P = new pizzaA ();
}
Else if (type = "B ")
{
P = new pizzaB ();
}
Return p;
}
}
Public class pizzaStore
{
SimplePizzaFactory factory;
Public pizzaStore (simplePizzaFactory factory)
{
This. factory = factory;
}
Public pizza OrderPizza (string type)
{
Return factory. createPizza (type );
// Do somethingelse
}
}
Class Program
{
Static void Main (string [] args)
{
SimplePizzaFactory factory = new simplePizzaFactory ();
PizzaStore store = new pizzaStore (factory );
Store. OrderPizza ("");
Console. Read ();
}
}

// Design Pattern principle: dependent on abstraction, not specific classes

// Factory method mode
// Defines an interface for object creation, but the subclass determines which class to instantiate
// The Factory method delays class Instantiation to subclass
Public abstract class pizza
{}
Public class pizzaA: pizza
{}
Public class pizzaB: pizza
{}
// This is the abstract creator class, which defines an abstract factory Method
// Let the subclass implement this method to create a product
Public abstract class pizzaStore
{
Protected abstract pizza CreatePizza (string type );
Public pizza OrderPizza (string type)
{
Pizza p = CreatePizza (type );
// Do somethingelse
Return p;
}
}
Public class StoreA: pizzaStore
{
Protected override pizza CreatePizza (string type)
{
If (type = "")
{
Return new pizzaA ();
}
Else if (type = "B ")
{
Return new pizzaB ();
}
Else return null;
}
}
Class Program
{
Static void Main (string [] args)
{
PizzaStore storeA = new StoreA ();
StoreA. OrderPizza ("");
Console. Read ();
}
}

 

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.