• Türkçe (Türkiye)
    • English (United States)
    • العربية (مصر)
    • Deutsch (Deutschland)
    • Español (España, alfabetización internacional)
    • français (France)
    • हिंदी (भारत)
    • italiano (Italia)
    • 日本語 (日本)
    • 한국어 (대한민국)
    • Nederlands (Nederland)
    • polski (Polska)
    • русский (Россия)
    • ไทย (ไทย)
    • Tiếng Việt (Việt Nam)
    • 中文(中华人民共和国)
    • 中文(香港特別行政區)
  • Oturum açma
  • Kayıt ol
DotNetAge - Mvc & jQuery CMS
Kenar çubuğunu gizle

Factory method


Definition



Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

UML class diagram





Participants



The classes and/or objects participating in this pattern are:
  • Product - defines the interface of objects the factory method creates
  • ConcreteProduct - implements the Product interface
  • Creator (Document)
**declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
**may call the factory method to create a Product object.
  • ConcreteCreator - overrides the factory method to return an instance of a ConcreteProduct.

The job of the Factory design pattern is to create concrete sub classes. You can see the Factory design pattern used throughout the .NET Framework.

The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses." Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex, for example if it depends on settings in configuration files or on user input.

Sample code in C#




// A Simple Interface

public interface IVehicle
{
void Drive(int miles);
}


// The Vehicle Factory
public class VehicleFactory
{
public static IVehicle getVehicle(string Vehicle)
{
switch (Vehicle) {
case "Car":
return new Car();
case "Lorry":
return new Lorry();
default:
throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
break;
}
}
}

// A Car Class that Implements the IVehicle Interface
public class Car : IVehicle
{
public void IVehicle.Drive(int miles)
{
// Drive the Car
}
}

// A Lorry Class that Implements the IVehicle Interface

public class Lorry : IVehicle
{
public void IVehicle.Drive(int miles)
{
// Drive the Lorry
}
}

 


    Average:
  • Okur
    (1452)
  • Permalink
Paylaşmak için:

Tag cloud

Anything in here will be replaced on browsers that support the canvas element