Java设计模式之工厂模式

其实工厂模式跟策略模式有点相似,只不过,策略模式是通过中Contex调用具体实现类的相应方法,而工厂模式是生成实现类的实例。


package com.pocketdigi.patterns.factory;

public interface Human {
    public void laugh();
    public void cry();
}

package com.pocketdigi.patterns.factory;

public class YellowHuman implements Human {
    /**
     * 不加public 使得在外包无法new
     */
    YellowHuman()
    {
        
    }
    @Override
    public void laugh() {
        // TODO Auto-generated method stub
        System.out.println("黄色人种笑");
    }

    @Override
    public void cry() {
        // TODO Auto-generated method stub
        System.out.println("黄色人种哭");
    }
}

package com.pocketdigi.patterns.factory;

public class BlackHuman implements Human {
    /**
     * 不加public 使得在外包无法new
     */
    BlackHuman()
    {
        
    }
    @Override
    public void laugh() {
        // TODO Auto-generated method stub
        System.out.println("黑色人种笑");
    }

    @Override
    public void cry() {
        // TODO Auto-generated method stub
        System.out.println("黑色人种哭");
    }
}

工厂:


package com.pocketdigi.patterns.factory;


public class HumanFactory {
    public static Human createHuman(Class c)
    {
        try {
            Object obj=c.newInstance();
            return (Human)obj;
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static BlackHuman createBlackHuman()
    {
        return (BlackHuman)createHuman(BlackHuman.class);
    }
    
    public static YellowHuman createYellowHuman()
    {
        return (YellowHuman)createHuman(YellowHuman.class);
    }
}

调用:


        Human human=HumanFactory.createHuman(YellowHuman.class);
        human.laugh();
        HumanFactory.createBlackHuman().laugh();

© 2014, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记

发表评论

电子邮件地址不会被公开。 必填项已用*标注