简单工厂模式:由一个工厂对象决定创建出哪一种类的实例。
1.抽象类
public abstract class People { public abstract void doSth(); }
2.具体类
public class Man extends People{ @Override public void doSth() { System.out.println("I'm a man,I'm coding."); } }
3.具体类
public class Girl extends People{ @Override public void doSth() { System.out.println("I'm a girl,I'm eating."); } }
4.工厂
public class PeopleFactory { public static People getSpecificPeople(String type){ if("A-Man".equals(type)){ return new Man(); }else if("B-Girl".equals(type)){ return new Girl(); }else { return null; } } }
5.测试代码
public class PeopleTestDemo { public static void main(String[] args) { People man = PeopleFactory.getSpecificPeople("A-Man"); Objects.requireNonNull(man,"对象不存在."); man.doSth(); People girl = PeopleFactory.getSpecificPeople("B-Girl"); Objects.requireNonNull(girl,"对象不存在"); girl.doSth(); People foodie = PeopleFactory.getSpecificPeople("Foodie"); Objects.requireNonNull(foodie,"对象不存在"); foodie.doSth(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。