抽象工厂模式

抽象工厂

- interface IProduct1 {
-     public void show();
- }
- interface IProduct2 {
-     public void show();
- }
-
- class Product1 implements IProduct1 {
-     public void show() {
-         System.out.println("这是1型产品");
-     }
- }
- class Product2 implements IProduct2 {
-     public void show() {
-         System.out.println("这是2型产品");
-     }
- }
-
- interface IFactory {
-     public IProduct1 createProduct1();
-     public IProduct2 createProduct2();
- }
- class Factory implements IFactory{
-     public IProduct1 createProduct1() {
-         return new Product1();
-     }
-     public IProduct2 createProduct2() {
-         return new Product2();
-     }
- }
-//每次调用都会创建一个新的factory对象,并不高效,必要时可结合单例使用
- public class Client {
-     public static void main(String[] args){
-         IFactory factory = new Factory();
-         factory.createProduct1().show();
-         factory.createProduct2().show();
-     }
- }

抽象工厂模式和工厂模式的区别

  1. 抽象工厂是工厂模式的升级版
  2. 抽象工厂可以抽象不同类别(不同的产品抽象类)的产品,工厂模式 抽象单一类别(相同的产品抽象类)的产品