工厂方法模式之JAVA实现

时间:2014-10-10 20:03:24   收藏:0   阅读:239

 

//Product

interface Human {
    public void talk();
}

class American implements Human {
    @Override
    public void talk() {
        System.out.println("American speak English.");
    }
}

class Chinese implements Human {
    @Override
    public void talk() {
        System.out.println("Chinese speak Chinese.");
    }
}

class Korean implements Human {
    @Override
    public void talk() {
        System.out.println("Korean speak Korean.");
    }
}

 

//Factory

abstract class HumanFactory {
    abstract Human create();
}

class ChineseFactory extends HumanFactory {
    public Human create() {
        return new Chinese();
    }
}

class AmericanFactory extends HumanFactory {
    public Human create() {
        return new American();
    }
}

class KoreanFactory extends HumanFactory {
    public Human create() {
        return new Korean();
    }
}

 

//Test

public class FactoryMethodPattern {
    /**
     * @param args
     */
    public static void main(String[] args) {
        HumanFactory factory = new ChineseFactory();
        Human human = factory.create();
        human.talk();
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!