多态-工厂模式

1 package 多态.工厂模式;
2 
3 
4 public  abstract class Person {
5 
6     abstract void sayhello();
7 
8 }
package 多态.工厂模式;

public class Chinese extends Person {


    @Override
    void sayhello() {
        System.out.println("你好");
    }
}
package 多态.工厂模式;

/**
 * 美国人类
 */
public class America extends Person{
    void sayhello() {
        System.out.println("你好");
    }
}
package 多态.工厂模式;

/**
 * 工厂类  通过工厂模式拿到对象
 */
public class Factory {

    public Person getperson(String ch){

        if("china".equals(ch)){

            return new Chinese(); // 返回new一个对象 返回的是对象的地址 相当于输入China 输出了Person china = new Chinese()

        }else {

            return new America();

        }

    }

}
package 多态.工厂模式;

public class TestFactory {
    public static void main(String[] args) {
        Factory factory = new Factory();
        Person china = factory.getperson("china");
        china.sayhello();
    }
}

 

posted @ 2019-04-13 20:36  后天2333  阅读(355)  评论(0编辑  收藏  举报