设计模式

单例模式

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

工厂模式

interface Shape {
    void draw();
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}

class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }
        return null;
    }
}

观察者模式

import java.util.ArrayList;
import java.util.List;

interface Observer {
    void update(String message);
}

class Subject {
    private List<Observer> observers = new ArrayList<>();
    private String message;

    public void attach(Observer observer) {
        observers.add(observer);
    }

    public void notifyAllObservers() {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }

    public void setMessage(String message) {
        this.message = message;
        notifyAllObservers();
    }
}

class ConcreteObserver implements Observer {
    private String name;

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

    @Override
    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

JDK动态代理

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Hello {
    void sayHello();
}

class HelloImpl implements Hello {
    @Override
    public void sayHello() {
        System.out.println("Hello World");
    }
}

class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method call");
        Object result = method.invoke(target, args);
        System.out.println("After method call");
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        Hello hello = new HelloImpl();
        MyInvocationHandler handler = new MyInvocationHandler(hello);
        Hello proxy = (Hello) Proxy.newProxyInstance(
                hello.getClass().getClassLoader(),
                hello.getClass().getInterfaces(),
                handler);
        proxy.sayHello();
    }
}

基于CGLIB动态代理

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

class Hello {
    public void sayHello() {
        System.out.println("Hello World");
    }
}

class MyMethodInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("Before method call");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("After method call");
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Hello.class);
        enhancer.setCallback(new MyMethodInterceptor());
        Hello hello = (Hello) enhancer.create();
        hello.sayHello();
    }
}

装饰器模式和代理模式的区别

装饰器模式和代理模式都属于结构型设计模式,它们都可以在不改变原有对象的基础上,为对象添加新的功能。但是,它们之间还是有一些区别的。

装饰器模式主要用于在运行时动态地为对象添加额外的职责。它通过创建一个装饰器类来包装原有对象,然后在装饰器类中重写原有对象的方法,并在方法中添加新的逻辑。这样,当我们调用装饰器对象的方法时,就可以实现在不改变原有对象的基础上为其添加新的功能。

代理模式主要用于控制对原有对象的访问。它通过创建一个代理类来代表原有对象,并在代理类中实现与原有对象相同的接口。这样,当我们调用代理对象的方法时,就可以在不直接访问原有对象的情况下控制对其的访问。

总之,装饰器模式和代理模式都可以为对象添加新的功能,但它们关注点不同:装饰器模式关注如何在不改变原有对象的基础上为其添加新功能;而代理模式关注如何控制对原有对象的访问。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 学习设计模式不是一蹴而就的事情,需要长时间的积累,在平时写代码的时候多思考,学习设计模式的时候也不要死记硬背,要了...
    tanghomvee阅读 5,466评论 0 2
  • 结构型设计模式汇总 结构型设计模式名称 结构型设计模式主要包括 7 大类: 代理模式 桥接模式 装饰器模式 适配器...
    allen218阅读 3,587评论 0 0
  • 设计模式概述 在学习面向对象七大设计原则时需要注意以下几点:a) 高内聚、低耦合和单一职能的“冲突”实际上,这两者...
    彦帧阅读 9,188评论 0 14
  • 学习并理解 23 种设计模式 设计模式 Design Pattern 是一套被反复使用、多数人知晓的、经过分类编目...
    Code_Narrator阅读 4,736评论 0 1
  • 关于这篇文章本人的体悟,要彻底理解面向对象思想,一切从面向对象的思想触发去理解学习。摒弃面向过程的业务思维将实际工...
    牧童US阅读 4,662评论 0 4

友情链接更多精彩内容