提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
工厂模式是我们最常用的模式了,著名的Jive论坛 ,就大量使用了工厂模式,工厂模式在Java程序系统可以说是随处可见。
为什么工厂模式是如此常用?因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a=new A() 工厂模式也是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑实用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量
package com.lyz.design.abstractfactory; /** * 这个接口就是类图中标识的 * AbstractFactory抽象工厂 * @author liuyazhuang * */ public interface IAnimalFactory { /** * 定义创建Icat接口实例的方法 * @return */ ICat createCat(); /** * 定义创建IDog接口实例的方法 * @return */ IDog createDog(); }
package com.lyz.design.abstractfactory; /** * IAnimalFactory抽象工厂的实现类 * @author liuyazhuang * */ public class WhiteAnimalFactory implements IAnimalFactory { public ICat createCat() { return new WhiteCat(); } public IDog createDog() { return new WhiteDog(); } }
package com.lyz.design.abstractfactory; /** * IAnimalFactory抽象工厂的实现类 * @author liuyazhuang */ public class BlackAnimalFactory implements IAnimalFactory { @Override public ICat createCat() { return new BlackCat(); } public IDog createDog() { return new BlackDog(); } }
package com.lyz.design.abstractfactory; /** * 类图中定义的AbstractProduct * 指定工厂生产的产品 * @author liuyazhuang * */ public interface ICat { /** * 定义方法 */ void eat(); }
package com.lyz.design.abstractfactory; /** * 类图中定义的AbstractProduct * 指定工厂生产的产品 * @author liuyazhuang * */ public interface IDog { /** * 定义方法 */ void eat(); }
package com.lyz.design.abstractfactory; /** * ICat接口的实现类 * @author liuyazhuang * */ public class BlackCat implements ICat { @Override public void eat() { System.out.println("The black cat is eating!"); } }
package com.lyz.design.abstractfactory; /** * IDog的实现类 * @author liuyazhuang */ public class BlackDog implements IDog { @Override public void eat() { System.out.println("The black dog is eating"); } }
package com.lyz.design.abstractfactory; /** * ICat的实现类 * @author liuyazhuang * */ public class WhiteCat implements ICat { @Override public void eat() { System.out.println("The white cat is eating!"); } }
package com.lyz.design.abstractfactory; /** * IDog的实现类 * @author liuyazhuang * */ public class WhiteDog implements IDog { @Override public void eat() { System.out.println("The white dog is eating!"); } }
package com.lyz.design.abstractfactory; /** * 测试类 * @author liuyazhuang * */ public class Test { public static void main(String[] args) { IAnimalFactory blackAnimalFactory = new BlackAnimalFactory(); ICat blackCat = blackAnimalFactory.createCat(); blackCat.eat(); IDog blackDog = blackAnimalFactory.createDog(); blackDog.eat(); IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory(); ICat whiteCat = whiteAnimalFactory.createCat(); whiteCat.eat(); IDog whiteDog = whiteAnimalFactory.createDog(); whiteDog.eat(); } }
The black cat is eating! The black dog is eating The white cat is eating! The white dog is eating!
浅谈JAVA设计模式之——抽象工厂模式(AbstractFactoty)
原文地址:http://blog.csdn.net/l1028386804/article/details/45440309