设计模式
设计原则
- 多用对象组合, 少用继承(注意: 是少用而不是不用). 所谓对象组合, 就是让对象作为类的成员变量, 通过构造函数或set方法给类对象的实例变量赋值. 所以说一般抽象工厂方法都是联合在一起使用的 这样的系统结构更加具有灵活性和弹性.
- 针对抽象编程, 不针对实现编程. 当设计一个软件系统的时候, 要尽可能地对系统中出现的各种事物进行抽象, 从而建立基础的抽象底层. 如本例中对食物的抽象, AbstractBaseFood是所有食物的抽象基类, 相同的属性和方法可以在抽象基类中实现, 这样所有的子类都能复用; IFood是所有食物的抽象接口, 用于实现共同的方法. 有了抽象, 对新增功能不会对原系统的稳定性千万影响, 系统更加模块化, 软件更加易复用.
- 产品对象通过工厂暴露的方法创建. 如客户类Customer中, 没有使用创建对象实例的语句, 而是调用抽象工厂暴露的方法获得对象实例, 创建具体对象实例的工作全部都是在具体工厂中实现的.
使用场合
- 创建产品家族, 相关产品集合在一起使用的时候;
- 想要提供一个产品类库, 并只想显示其接口而不是实现时;
- 通过组合的方式使用工厂时.
- 用于创建相关或者依赖对象的家族, 而不需要指定具体实现类. 这就是说, 抽象工厂的任务就是负责创建一组产品的接口, 而接口中的每一个接口方法都负责产生一种产品.
与工厂方法模式的区别
- 工厂方法模式通过继承的方式实现应用程序的解耦, 而抽象工厂模式则通过对象组合的方式实现应用程序解耦.
- 工厂方法模式用来创建一个抽象产品, 具体工厂实现工厂方法来创建具体产品, 而抽象工厂模式用来创建一个产品家庭的抽象类型.
实现代码
//食品基类 public class AbstractBaseFood02 { private String kind; private int num; private float price; public float totalPrice() { return this.num * this.price; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
//抽象食品接口 public interface IFood02 { void printMessage(); }
//汉堡基类 public class Hambugr02 extends AbstractBaseFood02 implements IFood02 { public void printMessage() { System.out.println("--" + this.getKind() + "风味汉堡, \t 单价: " + this.getPrice() + ", \t 数量: " + this.getNum() + ", \t 合计: " + this.totalPrice()); } }
//薯条基类 public class FrenchFries02 extends AbstractBaseFood02 implements IFood02 { public void printMessage() { System.out.println("--" + this.getKind() + "风味薯条, \t 单价: " + this.getPrice() + ", \t 数量: " + this.getNum() + ", \t 合计: " + this.totalPrice()); } }
//汉堡具体类 public class ChinaHamugr02 extends Hambugr02 { ChinaHamugr02(int num) { this.setNum(num); this.setKind("麻辣风味"); this.setPrice(16.0f); } }
//薯条具体类 public class ChinaFrenchFries02 extends FrenchFries02 { ChinaFrenchFries02(int num) { this.setNum(num); this.setKind("麻辣风味"); this.setPrice(16.0f); } }
//抽象食品工厂 public interface IKFCFactory02 { Hambugr02 createHambuger(int num); FrenchFries02 createFrenchFries(int num); }
//具体工厂 public class ChinaKFCFactory02 implements IKFCFactory02 { public Hambugr02 createHambuger(int num) { return new ChinaHamugr02(num); } public FrenchFries02 createFrenchFries(int num) { return new ChinaFrenchFries02(num); } }
//客户端 public class AbstractFactoryMain { public static void main(String[] args) { IKFCFactory02 factory = new ChinaKFCFactory02(); Customer02 customer = new Customer02(factory); customer.orderFrenchFries(3); customer.orderHamburg(2); } }