Vs 2008
The factory method mode allows you to create a series of classes that belong to the same product system. In addition, unlike the general simple factory, the factory method mode creates products by sub-classes. To add new products, you do not need to modify the originalCodeTo add a new factory subclass.
1. Mode UML diagram
2. Application
ProgramDifferent transportation tools need to be used to abstract the behavior of transportation tools into an interface, so these transportation tools form a product system with common behavior. Create a factory system for the product based on the concept of the factory method model.
Itransportation. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. factorymethod. BLL {
Public InterfaceItransportation{
VoidRun ();
}
}
Car. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. factorymethod. BLL {
Public Class Car: itransportation {
Itransportation members # Region Itransportation members
Public Void Run () {
Console. writeline ("I am a car, I am running");
}
# Endregion
}
}
Plane. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. factorymethod. BLL {
Public Class Plane: itransportation {
Itransportation members # Region Itransportation members
Public Void Run () {
Console. writeline ("I am a plane, I am running");
}
# Endregion
}
}
Itransportationfactory. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. factorymethod. BLL {
Public InterfaceItransportationfactory{
Itransportation create ();
}
}
Carfactory. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. factorymethod. BLL {
Public Class Carfactory: itransportationfactory {
Itransportationfactory members # Region Itransportationfactory members
Public Itransportation create () {
Return NewCar ();
}
# Endregion
}
}
Planefactory. CS
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Namespace Designpattern. factorymethod. BLL {
Public Class Planefactory: itransportationfactory {
Itransportationfactory members # Region Itransportationfactory members
Public Itransportation create () {
Return NewPlane ();
}
# Endregion
}
}
Client
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using Designpattern. factorymethod. BLL;
Namespace Designpattern. factorymethod {
Class Program {
Static Void Main ( String [] ARGs) {
Itransportationfactory carfactory = New Carfactory ();
Itransportation car = Carfactory. Create ();
Car. Run ();
Itransportationfactory planefactory = New Planefactory ();
Itransportation plane = Planefactory. Create ();
Plane. Run ();
}
}
}
Output