Factory pattern is used to create objects. This pattern falls
under creational patterns of GOF (Gang of Four) Patterns. In simple term
factory used to create products and in software term factory used to create
objects.
When to use –
When applications grow, we create more and more objects
which increases complexity and becomes more difficult to maintain. To reduce complexity,
we need to create objects in structured manner so that we can easily maintain
them. Factory pattern provides easy way to create objects as per your need and
also help you to write flexible and easy to maintain code.
Code –
public enum ResourceType
{
DotNet,
Java
}
public interface IResource
{
string DoWork();
}
public class DotNet : IResource
{
public string
DoWork()
{
return "I'm
writing Dotnet code.";
}
}
public class Java : IResource
{
public string
DoWork()
{
return "I'm
writing Java code.";
}
}
public static class ResourceFactory
{
public static IResource
GetResource(ResourceType resourceType)
{
IResource
resource;
switch (resourceType)
{
case ResourceType.DotNet:
resource = new DotNet();
return
resource;
case ResourceType.Java:
resource = new Java();
return
resource;
default:
resource = null;
break;
}
return resource;
}
}
class Program
{
static void Main(string[] args)
{
IResource
myResource = ResourceFactory.GetResource(ResourceType.DotNet);
Console.WriteLine(myResource.DoWork());
myResource = ResourceFactory.GetResource(ResourceType.Java);
Console.WriteLine(myResource.DoWork());
Console.ReadLine();
}
}
Output –
Above example demonstrates how Factory Pattern used to get different
types of resources as per customers need. This example can easily be extended
by adding more resources.
Advantages –
- Factory patterns implementation provides loose coupling between application and factory products.
- Easy to extend and maintain products. (Open-Closed Principle)
Disadvantages –
- Sometimes it makes code more difficult to read.
- Increases complexity if incorrectly used.
Hope this post helps you to understand Factory Pattern.
Please leave your feedback in comments below.
References –
See Also –
Creational Patterns
|
Structural Patterns
|
Behavioral Patterns
|
|
||
|
|
|
|
|
|
|
|
|
|
|
No comments:
Post a Comment