Wednesday, 21 August 2013

Factory method implementaion

Factory method implementaion

I have implemented Factory method as following:
class A
{
}
class A1:A
{
}
class A2:A
{
}
static class Factory
{
public static A GetInstance(int i)
{
if (i == 1)
return new A1();
else if (i == 2)
return new A2();
else
return null;
}
}
I want to use the Factory in the following class method f1(). The method
f1() will be called from its derived classes.I can go by the following
approaches:
Approach 1:
class MyClass
{
private A obj = null;
public void f1()
{
obj = Factory.GetInstance(1);
}
}
Approach 2:
class MyClass2
{
protected A obj { get; set; }
protected void f1()
{
obj = Factory.GetInstance(1);
}
}
Which approach is better? Do I need to make the properties and methods
protected? What the pros and cons of the approaches?

No comments:

Post a Comment