首页 > 代码库 > 工厂方法模式之JAVA实现

工厂方法模式之JAVA实现

 

//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();    }}

 

工厂方法模式之JAVA实现