设计模式(二):工厂模式

发布于:2024-04-26 ⋅ 阅读:(26) ⋅ 点赞:(0)

1. 工厂模式的介绍

工厂模式(Factory Pattern)属于创建型模式,它提供了一种创建对象的最佳方式。它在创建对象时提供了一种封装机制,将实际创建对象的代码与使用代码分离。

工厂模式中包含三种角色:

  • 抽象产品(Abstract Product):定义了产品的共同接口或抽象类,规定了产品对象的共同方法。
  • 具体产品(Concrete Product):实现了抽象产品接口,定义了具体产品的特定行为和属性。
  • 工厂( Factory):负责实际创建具体产品的对象。

2. 工厂模式的类图

在这里插入图片描述

3. 工厂模式的实现

3.1 第一步:创建一个抽象产品

package blog;

/**
 * 服饰
 */
public interface Cloth {
    void dress();
}

3.2 第二步:创建具体产品

package blog;

/**
 * 男装
 */
public class ManCloth implements Cloth {
    @Override
    public void dress() {
        System.out.println("男装");
    }
}
package blog;

/**
 * 女装
 */
public class WomanCloth implements Cloth {
    @Override
    public void dress() {
        System.out.println("女装");
    }
}

3.3 第三步:创建工厂

package blog;

/**
 * 工厂
 */
public class ClothFactory {
    public static Cloth create(String type) {
        try {
            Class<?> aClass = Class.forName(type);
            return (Cloth) aClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            return null;
        }
    }

}

3.4 第四步:使用工厂,传递类型信息获取对象

package blog;

/**
 * 使用工厂
 */
public class ClothFactoryDemo {
    public static void main(String[] args) {
        // 创建男装
        Cloth manCloth = ClothFactory.create("blog.ManCloth");
        manCloth.dress();
        // 创建女装
        Cloth womanCloth = ClothFactory.create("blog.WomanCloth");
        womanCloth.dress();
    }
}