工厂模式理解,手写一个Java工厂模式

Java面试 潘老师 8个月前 (09-06) 205 ℃ (0) 扫码查看

工厂模式(Factory Pattern)是一种创建型设计模式,它旨在定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中去完成。工厂模式可以分为三种主要类型:简单工厂、工厂方法和抽象工厂。

简单工厂模式:

简单工厂模式并不被认为是一个正式的设计模式,更多地是一种编程习惯。其实现思路是,在一个工厂类中根据传入的参数不同,返回不同的产品实例。这些产品实例通常都有一个共同的父类或接口。简单工厂适用于需要创建的对象较少或者客户端不关心对象创建过程的情况。

// 示例:创建一个绘图工具,可以绘制不同形状的图形
public interface Shape {
    void draw();
}

class CircleShape implements Shape {
    // ...
}

class RectShape implements Shape {
    // ...
}

class TriangleShape implements Shape {
    // ...
}

class ShapeFactory {
    public static Shape getShape(String type) {
        Shape shape = null;
        if (type.equalsIgnoreCase("circle")) {
            shape = new CircleShape();
        } else if (type.equalsIgnoreCase("rect")) {
            shape = new RectShape();
        } else if (type.equalsIgnoreCase("triangle")) {
            shape = new TriangleShape();
        }
        return shape;
    }
}

工厂方法模式:

工厂方法模式具有较好的封装性,它的核心思想是将对象的创建延迟到子类中完成。每个产品类都对应一个工厂类,通过工厂方法来创建产品对象。这样,客户端只需知道产品的抽象类或接口,而不需要关心具体的实现类,降低了模块间的耦合。工厂方法模式适用于需要根据条件选择不同产品类型的情况,具有良好的可扩展性。

// 示例:汽车工厂演示工厂方法模式
public interface Car {
    void brand();
    void speed();
    void price();
}

class Audi implements Car {
    // ...
}

class Auto implements Car {
    // ...
}

interface CarFactory {
    Car factory();
}

class AudiFactory implements CarFactory {
    public Car factory() {
        return new Audi();
    }
}

class AutoFactory implements CarFactory {
    public Car factory() {
        return new Auto();
    }
}

抽象工厂模式:

抽象工厂模式是工厂方法模式的扩展,它可以创建一组相关或相互依赖的对象,而不需要指定它们的具体类。抽象工厂的核心思想是提供一个创建一系列相关产品的接口,由具体的工厂类来实现。这种模式适用于需要创建多个相关对象,并且这些对象可能存在多个产品族的情况,具有较高的抽象层级。

// 示例:创建跨平台游戏的架构设计
public interface OperationController {
    void control();
}

public interface UIController {
    void display();
}

// Android 平台具体产品
class AndroidOperationController implements OperationController {
    // ...
}

class AndroidUIController implements UIController {
    // ...
}

// iOS 平台具体产品
class IosOperationController implements OperationController {
    // ...
}

class IosUIController implements UIController {
    // ...
}

// Windows Phone 平台具体产品
class WpOperationController implements OperationController {
    // ...
}

class WpUIController implements UIController {
    // ...
}

public interface SystemFactory {
    OperationController createOperationController();
    UIController createInterfaceController();
}

这些工厂模式的优点包括封装性、可扩展性、降低耦合度等,而缺点则可能包括增加类的数量、引入复杂性等。了解这些方面可以展示您对不同工厂模式的理解和应用考虑。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/javainterview/8849.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】