2 工厂模式

时间:2019-07-20
本文章向大家介绍2 工厂模式,主要包括2 工厂模式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1 工厂模式的应用场景

工厂模式主要是为了在不同的条件下创建不同的对象,以植物大战僵尸为例:有三种对象,当创建完对象后,在Function中根据接收到的名字调用不同的对象。

三种对象:

public class Bean {
    public void fight(){
        System.out.println( "绿豆fight");
    }
}
public class Ice {
    public void fight(){
        System.out.println( "冰豆fight");
    }
}
public class Wall {
    public void fight(){
        System.out.println( "果墙fight");
    }
}

Function类:

public class function {
    public void fight(String name){
        if ("Bean".equals(name)){
            Bean bean = new Bean();
            bean.fight();
        }else if ("Ice".equals(name)){
            Ice ice = new Ice();
            ice.fight();
        }else {
            Wall wall = new Wall();
            wall.fight();
        }
    }
}

main类:在main类中输入不同的名字就会调用对象的不同方法。

public class main {
    public static void main(String[] args) {
        new function().fight("Ice");
    }
}

0

原文地址:https://www.cnblogs.com/youngao/p/11218989.html