My understanding of Factory Method Pattern is (Correct me if i am wrong)
Factory Method Pattern
"Factory Method allow the client to delegates the product creation (Instance Creation) to the subclass".
There are two situation in which we can go for creating Factory Method pattern.
(i) When the client is restricted to the product (Instance) creation.
(ii) There are multiple products available.But a decision to be made which product instance need to be returned.
If you want to create Abstract Method pattern
Example :
public enum ORMChoice
{
L2SQL,
EFM,
LS,
Sonic
}
//Abstract Product
public interface IProduct
{
void ProductTaken();
}
//Concrete Product
public class LinqtoSql : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken:LinqtoSql");
}
}
//concrete product
public class Subsonic : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken:Subsonic");
}
}
//concrete product
public class EntityFramework : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken:EntityFramework");
}
}
//concrete product
public class LightSpeed : IProduct
{
public void ProductTaken()
{
Console.WriteLine("OR Mapping Taken :LightSpeed");
}
}
public class Creator
{
//Factory Method
public IProduct ReturnORTool(ORMChoice choice)
{
switch (choice)
{
case ORMChoice.EFM:return new EntityFramework();
break;
case ORMChoice.L2SQL:return new LinqtoSql();
break;
case ORMChoice.LS:return new LightSpeed();
break;
case ORMChoice.Sonic:return new Subsonic();
break;
default: return null;
}
}
}
**Client**
Button_Click()
{
Creator c = new Creator();
IProduct p = c.ReturnORTool(ORMChoice.L2SQL);
p.ProductTaken();
}
Is my understanding of Factory Method is correct?
What you have there is actually more of an Abstract Factory Pattern, only that you factory (Creator
) is not abstract. The factor method pattern is specifically useful for subclassing:
class A {
public:
A() : m_Member( GetMember() )
{
}
protected:
virtual ISomeInterface * GetMember() { // default impl here }
private:
ISomeInterface * m_Member;
}
Now subclasses of A
can override GetMember
to make the superclass use a specific implementation of ISomeInterface
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With