1.抽象工厂模式的定义及使用场景
抽象工厂也是创建型设计模式之一。为创建一组相关或者是相互依赖的对象提供一个接口,而不需要指定他们的具体类。一个对象族有相同约束时可以使用抽象工厂模式。
2.抽象工厂模式的优缺点
2.1优点
良好封装性,低耦合
产品族内具有约束性,且为非公开状态
2.2缺点
产品族的扩展非常困难,需要修改抽象工厂及其实现,违背了开闭原则。但工厂的扩展是灵活的。
3.抽象工厂模式的实现方式
ProductA
public abstract class ProductA {
public abstract void excute();
}
ProductA1
public class ProductA1 extends ProductA {
@Override
public void excute() {
System.out.println("ProductA1excute!");
}
}```
ProductA2
public class ProductA2 extends ProductA {
@Override
public void excute() {
System.out.println("ProductA2excute!");
}
}```
ProductB
public abstract class ProductB {
public abstract void excute();
}```
ProductB1
public class ProductB1 extends ProductB {
@Override
public void excute() {
System.out.println("ProductB1excute!");
}
}```
ProductB2
public class ProductB2 extends ProductB {
@Override
public void excute() {
System.out.println("ProductB2excute!");
}
}```
Factory
public abstract class Factory {
public abstract <T extends ProductA> T createA();
public abstract <T extends ProductB> T createB();
}```
ConcreteOneFactory
public class ConcreteOneFactory extends Factory {
@Override
public <T extends ProductA> T createA() {
ProductA product = null;
try {
product = new ProductA1();
} catch (Exception e) {
e.printStackTrace();
}
return (T) product;
}
@Override
public <T extends ProductB> T createB() {
ProductB1 product = null;
try {
product = new ProductB1();
} catch (Exception e) {
e.printStackTrace();
}
return (T) product;
}
}```
ConcreteTwoFactory
public class ConcreteTwoFactory extends Factory {
@Override
public <T extends ProductA> T createA() {
ProductA2 product = null;
try {
product = new ProductA2();
} catch (Exception e) {
e.printStackTrace();
}
return (T) product;
}
@Override
public <T extends ProductB> T createB() {
ProductB2 product = null;
try {
product = new ProductB2();
} catch (Exception e) {
e.printStackTrace();
}
return (T) product;
}
}```
Test
public class Test {
public static void main(String args[]) {
Factory fOne = new ConcreteOneFactory();
Factory fTwo = new ConcreteTwoFactory();
ProductA a1 = fOne.createA();
ProductB b1 = fOne.createB();
a1.excute();
b1.excute();
ProductA a2 = fTwo.createA();
ProductB b2 = fTwo.createB();
a2.excute();
b2.excute();
}
}```
出处:http://huangjunbin.com/page/3/
网友评论