Quantcast
Channel: TechnoAhead
Viewing all articles
Browse latest Browse all 9

Design Patterns - Factory Pattern

$
0
0

Factory pattern is used to solve the problem of exposing the actual type to the client and also useful to decouple the client code from the actual functional code, that means the client need to aware of the what are all the actual possibilities that a actual application has. see the below example

 

In this client has a very tight couple code which has the four different operations, so the client takes the mode, value1 and value2 as a input parameter based on the mode it actually calls the corresponding operations, so here there are two problems are there.

1. There are lot of new keywords used.

2. The client must be aware of all the operations.

So if we add a another operation, the client code must be changed and it needs to be re-compiled to work, so how to solve this ? here comes the factory patter. lets have a look on below

 

we have created a interface and moved our operation implementation to the ICalculatorInterface.cs file, so this interface will be linked to our operation class and those classes will have their own implementations like the blow one.

 

now we are going to create a factory class, in that factory class we have the method(GetOperationClient) which will give the proper class to the client for its operation.

 

 

Now see our client code, its very simple, we have reduced so many lines of the code.

So here the client is no need to worry about the what are all the operations are available and it doesn't need to compile again, only the client needs the vision is about the Factory which will return the operation based on the mode.

ok i hope you are understand, please feel free to comment and ask if you need any details.

DownloadSourceCode :CalculationClient-FactoryPattern.zip (26.37 kb)


Viewing all articles
Browse latest Browse all 9

Latest Images

Trending Articles





Latest Images