Design Patterns - Simple Factory Pattern

  It is to create a factory class to create instances of some classes that implement the same interface. The essence of the simple factory pattern is that a factory class dynamically decides which instance of the product class (these product classes inherit from a parent class or interface) should be created according to the incoming parameters.

Sample code:
/**
 * The abstract interface human of the product
 * @author liaowp
 *
 */
public interface Human {
    
    public void say();

}

/**
 * man
 * @author liaowp
 *
 */
public class Man implements Human {

    /* say method
     * @see com.roc.factory.Human#say()
     */
    @Override
    public void say() {
        System.out.println("man");
    }

}

/**woman
 * @author liaowp
 *
 */
public class Woman implements Human {

    /* say method
     * @see com.roc.factory.Human#say()
     */
    @Override
    public void say() {
        System.out.println("女人");
    }

}

/**
 * Simple factory
 * @author liaowp
 *
 */
public class SampleFactory {
    public static Human makeHuman(String type){
        if(type.equals("man")){
            Human man = new Man();
            return man;
        }else if(type.equals("womman")){
            Human woman = new Woman();
            return woman;
        }else{
            System.out.println("Cannot be produced");
            return null;
        }            
    }
}

/**
 * Simple factory radiation implementation
 * @author liaowp
 *
 */
public class SampleFactory1 {
    public static Human makeHuman(Class c){
        Human human = null;
        try {
            human = (Human) Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            System.out.println("Abstract class or interface is not supported");
            e.printStackTrace ();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
            System.out.println("Insufficient permissions, i.e. cannot access private objects");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("Class does not exist");
            e.printStackTrace ();
        }    
        return human;
    }
}

public class Client {
    public static void main(String[] args) {
//        Human man = SampleFactory.makeHuman("man");
//        man.say();
//        Human womman = SampleFactory.makeHuman("womman");
// womman.say ();
//        Human test = SampleFactory.makeHuman("tttt");
        
        Human man = SampleFactory1.makeHuman(Man.class);
        man.say();
        Human woman = SampleFactory1.makeHuman(Woman.class);
        woman.say();
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326615203&siteId=291194637