Factory Method Design Pattern



This is a creational design pattern.
This is used to create an object based on some logic. The object creation logic is hidden from the client. The method which returns the object is called factory method.
This factory pattern is pretty simple. Client asks for the object which is required and pass some argument to identity what it needs exactly, then it gets the desired object. The client is not bothered how the object is getting created.
The advantage in this pattern is, new type of Objects can be added in future without changing any code. Only we need to add to the factory.
Example in JAVA- SaxParserFactory.

Let’s take an example.  Suppose we need a factory for connection. The connection can be multiple types e.g. serial, ip. Now the factory will create the object based on request and return to the client.

package designpattern;

interface Channel {
      public void connect();
}

class SerialChannel implements Channel {
      public void connect() {
            System.out.println("Connecting serial channel");
      }
}

class IpChannel implements Channel {
      public void connect() {
            System.out.println("Connecting ip channel");
      }
}

class ChannelFactory {
      public Channel getChannel(String channelType) {
            Channel channel = null;
            if ("serial".equals(channelType)) {
                  channel = new SerialChannel();
            } else if ("ip".equals(channelType)) {
                  channel = new IpChannel();
            }
            return channel;
      }
}

public class FactoryMethodPattern {
      public static void main(String[] args) {
            ChannelFactory channelFactory = new ChannelFactory();
            // Client wants serial channel
            Channel serialChannel = channelFactory.getChannel("serial");
            serialChannel.connect();
            // Client wants ip channel
            Channel ipChannel = channelFactory.getChannel("ip");
            ipChannel.connect();
      }
}

No comments:

Post a Comment