这篇文章主要介绍了java设计模式之简单工厂模式的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
简单工厂模式:由一个工厂对象决定创建出哪一种类的实例。
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(); } }
以上是Java实现简单工厂模式详解的详细内容。更多信息请关注PHP中文网其他相关文章!