返回

走进艺术家的画室:一文览尽14种设计模式的艺术应用

闲谈

设计模式与艺术的共舞

在软件开发的世界里,设计模式是程序员手中的画笔和调色板,他们用这些工具勾勒出软件系统的架构和行为。而艺术,作为人类创造力的巅峰,也为设计模式提供了源源不断的灵感。

单例模式:永恒的单品

单例模式就像一幅永恒的画作,无论时光流转,它都保持着同样的姿态。这种模式确保了一个类只能实例化一次,就像画作中只有一个主角,永远不会有第二个相同的主角。

public class Singleton {

    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

工厂方法模式:技艺精湛的画笔

工厂方法模式是一位技艺精湛的画师,能够根据不同的需求创造出各种各样的画笔。这些画笔就好比不同的对象,通过工厂方法模式的精心构造,我们可以灵活地创建出符合特定要求的对象。

public interface ShapeFactory {

    Shape createShape();
}

public class CircleFactory implements ShapeFactory {

    @Override
    public Shape createShape() {
        return new Circle();
    }
}

public class SquareFactory implements ShapeFactory {

    @Override
    public Shape createShape() {
        return new Square();
    }
}

抽象工厂模式:和谐统一的画风

抽象工厂模式就像一位统筹全局的艺术总监,能够协调各方资源,确保画作的风格保持统一。这种模式提供了一个创建相关或依赖对象家族的接口,而无需具体指定它们的类。

public interface GUIFactory {

    Button createButton();
    Checkbox createCheckbox();
}

public class MacFactory implements GUIFactory {

    @Override
    public Button createButton() {
        return new MacButton();
    }

    @Override
    public Checkbox createCheckbox() {
        return new MacCheckbox();
    }
}

public class WindowsFactory implements GUIFactory {

    @Override
    public Button createButton() {
        return new WindowsButton();
    }

    @Override
    public Checkbox createCheckbox() {
        return new WindowsCheckbox();
    }
}

建造者模式:一步步描绘的杰作

建造者模式就像一位耐心细致的画家,能够一步一步地描绘出复杂精美的画作。这种模式将一个复杂对象的构建与它的表示分离,使我们能够一步一步地构建对象,而无需担心对象的内部细节。

public class CarBuilder {

    private Car car;

    public CarBuilder() {
        car = new Car();
    }

    public CarBuilder withEngine(Engine engine) {
        car.setEngine(engine);
        return this;
    }

    public CarBuilder withBody(Body body) {
        car.setBody(body);
        return this;
    }

    public CarBuilder withWheels(Wheel[] wheels) {
        car.setWheels(wheels);
        return this;
    }

    public Car build() {
        return car;
    }
}

原型模式:复制艺术的魅力

原型模式就像一位复制大师,能够快速而准确地复制出与现有对象一模一样的副本。这种模式允许我们通过复制一个现有的对象来创建新的对象,而无需重新创建整个对象。

public class Prototype implements Cloneable {

    private String name;
    private int age;

    public Prototype(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

适配器模式:沟通不同世界的桥梁

适配器模式就像一座连接不同世界的桥梁,能够让原本无法沟通的系统和对象进行无缝的交互。这种模式允许我们将一个接口转换成另一个接口,使原本不兼容的接口能够一起工作。

public class Adapter implements Target {

    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

装饰器模式:画龙点睛的艺术

装饰器模式就像一位精通装饰之道的艺术家,能够在原有的画作上增添新的元素,使其更加丰富多彩。这种模式允许我们动态地向一个对象添加新的功能,而无需修改其原始代码。

public abstract class ShapeDecorator implements Shape {

    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }
}

public class ColoredShape extends ShapeDecorator {

    private String color;

    public ColoredShape(Shape decoratedShape, String color) {
        super(decoratedShape);
        this.color = color;
    }

    @Override
    public void draw() {
        decoratedShape.draw();
        System.out.println("Color: " + color);
    }
}

代理模式:艺术经纪人的角色

代理模式就像一位艺术经纪人,能够代表艺术家与外界进行沟通和合作。这种模式允许我们创建一个代理对象,来控制对另一个对象的访问。

public class Proxy implements Subject {

    private RealSubject realSubject;

    public Proxy(RealSubject realSubject) {
        this.realSubject = realSubject;
    }

    @Override
    public void request() {
        // Add additional functionality or access control before delegating to real subject
        realSubject.request();
    }
}

复合模式:构建艺术的层次结构

复合模式就像一位建筑师,能够将不同的元素组合成一个复杂的结构。这种模式允许我们将对象组合成树形结构,从而表示出“部分-整体”的层次关系。

public abstract class Component {

    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void display();
}

public class Composite extends Component {

    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void display() {
        System.out.println(name);
        for (Component child : children) {
            child.display();
        }
    }
}

享元模式:巧妙利用重复元素

享元模式就像一位节约成本的艺术家,能够通过重复利用相同的对象来减少内存的使用。这种模式允许我们将大量相似或相同的对象存储在一个池中,从而减少内存消耗。

public class FlyweightFactory {

    private Map<String, Flyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(String key) {
        Flyweight flyweight = flyweights.get(key);
        if (flyweight == null) {
            flyweight = new Flyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}

public class Flyweight {

    private String key;

    public Flyweight(String key) {
        this.key = key;
    }

    // ...
}

策略模式:应对不同场景的艺术创作

策略模式就像一位善于应对不同场景的艺术家,能够根据不同的情况采用不同的策略来进行创作。这种模式允许我们定义一系列算法,并将这些算法封装成对象,以便在不同的场景中使用。

public interface Strategy {

    void execute();
}

public class ConcreteStrategyA implements Strategy {

    @Override
    public void execute() {
        // ...
    }
}

public class ConcreteStrategyB implements Strategy {

    @Override
    public void execute() {
        // ...
    }
}

模板方法模式:构建创作的通用框架

模板方法模式就像一位经验丰富的导师,能够为艺术家提供一个通用的创作框架,帮助他们更高效地完成作品。这种模式定义了一个算法的骨架,允许子类在不改变算法结构的前提下重新定义算法的某些步骤。

public abstract class AbstractClass {

    public final void templateMethod() {
        step1();
        step2();
        step3();
    }

    protected abstract void step1();
    protected abstract void step2();
    protected abstract void step3();
}

public class ConcreteClassA extends AbstractClass {

    @Override
    protected void step1() {
        // ...