抽象工厂模式概念
抽象工厂模式属于创建型模式,它提供一个创建一系列相关或者相互依赖对象的接口,而无需指定它们具体的类。
抽象工厂模式与工厂模式的区别
- 工厂模式是针对一种产品
- 抽象工厂模式是针对多种产品(至少两种)
抽象工厂模式类图
抽象工厂模式实现
描述:抽象工厂模式一个工厂可以制作男款和女款的衣服,而工厂模式一个工厂只能制作一种款式的衣服
public abstract class AbstractClothesFactory {
abstract AbstractFemaleClothes createFClothes();
abstract AbstractMaleClothes createMClothes();
}
class ChildrenFactory extends AbstractClothesFactory{
@Override
AbstractFemaleClothes createFClothes() {
return new FChildrenClothes();
}
@Override
AbstractMaleClothes createMClothes() {
return new MChildrenClothes();
}
}
class MiddleAgeFactory extends AbstractClothesFactory{
@Override
AbstractFemaleClothes createFClothes() {
return new FMiddleAgeClothes();
}
@Override
AbstractMaleClothes createMClothes() {
return new MMiddleAgeClothes();
}
}
public abstract class AbstractFemaleClothes {
abstract void applayFor();
}
class FChildrenClothes extends AbstractFemaleClothes{
@Override
void applayFor() {
System.out.println("女孩穿的衣服");
}
}
class FMiddleAgeClothes extends AbstractFemaleClothes{
@Override
void applayFor() {
System.out.println("中年女性穿的衣服");
}
}
public abstract class AbstractMaleClothes {
abstract void applayFor();
}
class MChildrenClothes extends AbstractMaleClothes{
@Override
void applayFor() {
System.out.println("男孩穿的衣服");
}
}
class MMiddleAgeClothes extends AbstractMaleClothes{
@Override
void applayFor() {
System.out.println("中年男士穿的衣服");
}
}
public class Main {
public static void main(String[] args) {
AbstractClothesFactory childrenFactory = new ChildrenFactory();
AbstractClothesFactory middleAgeFactory = new MiddleAgeFactory();
AbstractFemaleClothes fChildrenClothes = childrenFactory.createFClothes();
fChildrenClothes.applayFor();
AbstractMaleClothes mChildrenClothes = childrenFactory.createMClothes();
mChildrenClothes.applayFor();
AbstractFemaleClothes fMiddleAgeClothes = middleAgeFactory.createFClothes();
fMiddleAgeClothes.applayFor();
AbstractMaleClothes mMiddleAgeClothes = middleAgeFactory.createMClothes();
mMiddleAgeClothes.applayFor();
}
}
输出结果如下
抽象工厂模式的优缺点
优点
- 便于交换产品系列,也就是说从儿童系列与中年系列之间的切换很容易,只需改变工厂即可
- 客户端与实例创建过程进行了分离,一切都交给工厂来处理并且产品系列具体类名也是不得知得(返回的是抽象接口)
缺点
当要在增加一种款式时,那么要修改之处很多(AbstractClothesFactory和它的具体实现类都要进行修改)
-_-没有天才,只有勤奋的天才!