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"); } }
采用上面的代码完成了基本要求,但对Function类进行分析每次都要有调用一个fight方法,能不能进行简化哪?可以使用接口,构造一个Plant接口
public interface Plant { public void fight(); }
这三种对象全部继承该接口,那么就可以利用一个接口可以具有多种具体实现的特性。
Bean类为例:
public class Bean implements Plant{ @Override public void fight(){ System.out.println( "绿豆fight"); } }
function类:
public class function { public void fight(String name){ Plant plant = null; if ("Bean".equals(name)){ plant = new Bean(); }else if ("Ice".equals(name)){ plant = new Ice(); }else { plant = new Wall(); } plant.fight(); } }
以上程序能满足基本要求,但仍有两点要注意:(1)如果function这样的类不止一个,每次增加一个新的场景function这样类就增加一次,那么就意味着我需要在每个这样的类中都要有上面的if else语句这样表明代码的复用性很低,(2)Bean、Ice这样的名字很容易就写错了,如果多个类中都有那么就会增加写错的几率。针对这两个问题解决方法就是简单工厂模式。
2 简单工厂模式
针对(1)创建一个工厂类,通过name创建对象,其实就是把function中的拷贝了一下
public class SimpleFactory { public static Plant createPlant(String name){ Plant plant = null; if ("Bean".equals(name)){ plant = new Bean(); }else if ("Ice".equals(name)){ plant = new Ice(); }else { plant = new Wall(); } return plant; } }
function类:这样对该类进行其他操作就方便了很多
public class function { public void fight(String name){ Plant plant = SimpleFactory.createPlant("name"); plant.fight(); } }
针对(2)可以创建一个常量类PlantNameConstant
public class PlantNameConstant { /** * 绿逗的名字 */ public static final String BEAN_NAME = "Bean"; /** * 蓝冰的名字 */ public static final String ICE_NAME = "Ice"; /** * 果墙的名字 */ public static final String WALL_NAME = "Wall"; }
这样优化后工厂类便可以进一步改进
public class SimpleFactory { public static Plant createPlant(String name){ Plant plant = null; if (PlantNameConstant.BEAN_NAME.equals(name)){ plant = new Bean(); }else if (PlantNameConstant.ICE_NAME.equals(name)){ plant = new Ice(); }else { plant = new Wall(); } return plant; } }
0