Simple factory pattern design patterns

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Simple factory pattern is the most simple factory pattern, also called static factory method pattern. Create it implements some kind of the same interface for instance, a factory to create multiple products through a conditional statement, create a logical product concentration in a factory, customers hear different parameter passing to the factory, to achieve the creation of different products to. The following:

Phone is an interface, which has a behavior is ring,   NokiaPhone and EricssonPhone respectively implement this interface, the client through the use of mobile phone incoming what type, and get different mobile phone. To achieve the following:

Phone.java:

 package org.designpattern.creational.simplefactory;

public interface Phone {

public void ring();

}

NokaiPhone.java

    package org.designpattern.creational.simplefactory;

    public class NokiaPhone implements Phone {

@Override

public void ring() {

// TODO Auto-generated method stub

System.out.println("nokia phone ring!");

}

    } 

  EricssonPhone.java

    package org.designpattern.creational.simplefactory;

    public class EricssonPhone implements Phone {

@Override

public void ring() {

// TODO Auto-generated method stub

System.out.println("ericsson phone ring!");

}

    } 

  PhoneFactory.java

    package org.designpattern.creational.simplefactory;

    public class PhoneFactory {

public Phone producePhone(String phoneType){

if("nokia".equals(phoneType))

return new NokiaPhone();

else if("ericsson".equals(phoneType))

return new EricssonPhone();

else return null;

}

    } 

If you will write two static methods of public static Phone produceNokiaPhone PhoneFactory (public), static produceEricssionPhone (Phone), the creation method we called static factory pattern, we use more or static factory pattern.  

  The use of a client class:

    package org.designpattern.creational.simplefactory;

    public class Main {

public static void main(String[] args){

NokiaPhone nokia = (NokiaPhone) new PhoneFactory().producePhone("nokia");

nokia.ring();

}

    } 

  The factory class focused all the products to create a logical, formed a powerful class know everything, obviously if the class does not work, the whole process will be affected. More important is that is not conducive to the expansion of the factory, if the application requires many types, is bound to cause the plant types of duties is similar, so we need more abstract, hence the factory method and abstract factory pattern.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Edgar at November 17, 2013 - 4:04 AM