什么是抽象工厂模式(AbstractFactroy)?

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

  1. 意图
    提供一个创建一系列相关或有依赖关系的对象的接口,而不用指定具体的类。
  2. 类图
    什么是抽象工厂模式(AbstractFactroy)?_第1张图片
  3. 实例
interface Factory {
    Type1 getType1(String type1);
    Type2 getType2(String type2);
}

abstract class AbstractFactory implements Factory {
    @Override
    public Type1 getType1(String type1) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Type2 getType2(String type2) {
        throw new UnsupportedOperationException();
    }
}

class Type1Factory extends AbstractFactory {
    @Override
    public Type1 getType1(String type1) {
        Type1 type11 = null;
        switch (type1) {
            case "impl1": type11 = new Type1Impl1(); break;
            case "impl2": type11 = new Type1Impl2(); break;
            case "impl3": type11 = new Type1Impl3(); break;
        }
        return type11;
    }
}

class Type2Factory extends AbstractFactory {
    @Override
    public Type2 getType2(String type2) {
        Type2 type21 = null;
        switch (type2) {
            case "impl1": type21 = new Type2Impl1(); break;
            case "impl2": type21 = new Type2Impl2(); break;
            case "impl3": type21 = new Type2Impl3(); break;
        }
        return type21;
    }
}


interface Type1 { }

class Type1Impl1 implements Type1 {}
class Type1Impl2 implements Type1 {}
class Type1Impl3 implements Type1 {}

interface Type2 { }

class Type2Impl1 implements Type2 {}
class Type2Impl2 implements Type2 {}
class Type2Impl3 implements Type2 {}

class FactoryImpl implements Factory {
    private Type1Factory type1Factory;
    private Type2Factory type2Factory;
    public FactoryImpl () {
        type1Factory = new Type1Factory();
        type2Factory = new Type2Factory();
    }

    @Override
    public Type1 getType1(String type1) {
        return type1Factory.getType1(type1);
    }

    @Override
    public Type2 getType2(String type2) {
        return type2Factory.getType2(type2);
    }
}
  1. 测试
class FactoryTest {
    public static void main(String[] args) {
        Factory factory = new FactoryImpl();
        System.out.println(factory.getType1("impl1"));
        System.out.println(factory.getType1("impl2"));
        System.out.println(factory.getType1("impl3"));
        System.out.println();
        System.out.println(factory.getType2("impl1"));
        System.out.println(factory.getType2("impl2"));
        System.out.println(factory.getType2("impl3"));
    }
}

运行结果:

designpattern.abstractfactory.Type1Impl1@6adca536
designpattern.abstractfactory.Type1Impl2@28f67ac7
designpattern.abstractfactory.Type1Impl3@2a18f23c

designpattern.abstractfactory.Type2Impl1@23223dd8
designpattern.abstractfactory.Type2Impl2@1b40d5f0
designpattern.abstractfactory.Type2Impl3@3c5a99da

想看更多吗?请访问:设计模式

你可能感兴趣的:(设计模式,java)