java设计模式-抽象工厂模式

本文介绍了抽象工厂模式的概念及其与工厂模式的区别,通过示例代码展示了如何使用抽象工厂模式创建一系列相关或相互依赖的对象,同时讨论了该模式的优点和缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

抽象工厂模式概念

  抽象工厂模式属于创建型模式,它提供一个创建一系列相关或者相互依赖对象的接口,而无需指定它们具体的类。


抽象工厂模式与工厂模式的区别
  • 工厂模式是针对一种产品
  • 抽象工厂模式是针对多种产品(至少两种)

抽象工厂模式类图

这里写图片描述


抽象工厂模式实现

描述:抽象工厂模式一个工厂可以制作男款和女款的衣服,而工厂模式一个工厂只能制作一种款式的衣服

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和它的具体实现类都要进行修改)

                                                         -_-没有天才,只有勤奋的天才!
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值