GoF 23

GoF 23

看了狂神视频之后自己实际操作总结的,狂神yyds

23种设计模式

  1. 单例(Singleton)模式:某个类只能生成一个实例,该类提供了一个全局访问点供外部获取该实例,其拓展是有限多例模式。
  2. 原型(Prototype)模式:将一个对象作为原型,通过对其进行复制而克隆出多个和原型类似的新实例。
  3. 工厂方法(Factory Method)模式:定义一个用于创建产品的接口,由子类决定生产什么产品。
  4. 抽象工厂(AbstractFactory)模式:提供一个创建产品族的接口,其每个子类可以生产一系列相关的产品。
  5. 建造者(Builder)模式:将一个复杂对象分解成多个相对简单的部分,然后根据不同需要分别创建它们,最后构建成该复杂对象。
  6. 代理(Proxy)模式:为某对象提供一种代理以控制对该对象的访问。即客户端通过代理间接地访问该对象,从而限制、增强或修改该对象的一些特性。
  7. 适配器(Adapter)模式:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
  8. 桥接(Bridge)模式:将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
  9. 装饰(Decorator)模式:动态的给对象增加一些职责,即增加其额外的功能。
  10. 外观(Facade)模式:为多个复杂的子系统提供一个一致的接口,使这些子系统更加容易被访问。
  11. 享元(Flyweight)模式:运用共享技术来有效地支持大量细粒度对象的复用。
  12. 组合(Composite)模式:将对象组合成树状层次结构,使用户对单个对象和组合对象具有一致的访问性。
  13. 模板方法(TemplateMethod)模式:定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。
  14. 策略(Strategy)模式:定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的改变不会影响使用算法的客户。
  15. 命令(Command)模式:将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。
  16. 职责链(Chain of Responsibility)模式:把请求从链中的一个对象传到下一个对象,直到请求被响应为止。通过这种方式去除对象之间的耦合。
  17. 状态(State)模式:允许一个对象在其内部状态发生改变时改变其行为能力。
  18. 观察者(Observer)模式:多个对象间存在一对多关系,当一个对象发生改变时,把这种改变通知给其他多个对象,从而影响其他对象的行为。
  19. 中介者(Mediator)模式:定义一个中介对象来简化原有对象之间的交互关系,降低系统中对象间的耦合度,使原有对象之间不必相互了解。
  20. 迭代器(Iterator)模式:提供一种方法来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。
  21. 访问者(Visitor)模式:在不改变集合元素的前提下,为一个集合中的每个元素提供多种访问方式,即每个元素有多个访问者对象访问。
  22. 备忘录(Memento)模式:在不破坏封装性的前提下,获取并保存一个对象的内部状态,以便以后恢复它。
  23. 解释器(Interpreter)模式:提供如何定义语言的文法,以及对语言句子的解释方法,即解释器。

单例模式

所谓单例模式就是某个类只能生成一个示例对象

  • 构造方法必须私有
  • 不能生成多个实例
  • 防止反射修改构造方法创建对象
  • 提供一个全局访问点供外部获取该实例

饿汉式

缺点:容易造成内存浪费

public class Hungry {
    /*
    private byte[] data1 = new byte[1024*1024];
    private byte[] data2 = new byte[1024*1024];
    private byte[] data3 = new byte[1024*1024];
    private byte[] data4 = new byte[1024*1024];
    */
    private Hungry(){
    }

    private final static Hungry HUNGRY = new Hungry();

    public static Hungry getInstance() {
        return HUNGRY;
    }
    
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                Hungry.getInstance();
            }).start();
        }
    }
}

懒汉式

缺点:多线程并发下不稳定

public class LazyMan {

    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + " ok");
    }

    private static LazyMan LAZYMAN;
	//创建对象的时候当对象为空才创建,避免浪费内存
    public static LazyMan getInstance(){
        if (LAZYMAN==null){
            LAZYMAN = new LazyMan();
        }
        return LAZYMAN;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                LazyMan.getInstance();
            }).start();
        }
    }
}

结果

Thread-0 ok
Thread-3 ok
Thread-2 ok

DCL懒汉式——双重锁模式

由于多线程下导致不稳定,我们可以用锁解决

public class LazyMan {

    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + " ok");
    }
	//      ↓↓↓↓↓↓↓↓
    private volatile static LazyMan LAZYMAN;

    public static LazyMan getInstance(){
        if (LAZYMAN==null){
            //锁LazyMan这个类,确保只有一个类
            synchronized (LazyMan.class){
                if (LAZYMAN==null){
                    LAZYMAN = new LazyMan();//new 这个操作不是原子性操作
                    /*
                    	1. 分配内存空间
                    	2. 执行构造方法,初始化对象
                    	3. 把这个对象执行这个空间
                    	单线程:123√,132√
                    	多线程:123√,132x
                    */
                    //多线程下如果出现指令重排就会导致出现问题
                    //所以就必须要避免指令重排,使用volatile
                }
            }
        }
        return LAZYMAN;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                LazyMan.getInstance();
            }).start();
        }
    }
}

内部类

public class Holder {
    private Holder(){

    }

    public static Holder getInstance(){
        return Inner.HOLDER;
    }

    public static class Inner {
        private static final Holder HOLDER = new Holder();
    }

}

以上三种均不安全(可破解,反射)

● 攻方:使用反射获取构造器再实例对象

public class LazyMan {

    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + " ok");
    }

    private volatile static LazyMan LAZYMAN;

    public static LazyMan getInstance(){
        if (LAZYMAN==null){
            synchronized (LazyMan.class){
                if (LAZYMAN==null){
                    LAZYMAN = new LazyMan();
                }
            }
        }
        return LAZYMAN;
    }

    public static void main(String[] args) throws Exception {
        LazyMan instance1 = LazyMan.getInstance();
        //获取类构造器
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        //无视构造器私有
        constructor.setAccessible(true);
        //创建一个新对象
        LazyMan instance2 = constructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);
    }
}

结果

main ok
main ok
LazyMan@1b6d3586
LazyMan@4554617c

● 守方:在构造器中加锁

public class LazyMan {

    private LazyMan(){
        if(LAZYMAN == null)
    }

    private volatile static LazyMan LAZYMAN;

    public static LazyMan getInstance(){
        if (LAZYMAN==null){
            synchronized (LazyMan.class){
                if (LAZYMAN==null){
                    LAZYMAN = new LazyMan();
                }
            }
        }
        return LAZYMAN;
    }

    public static void main(String[] args) throws Exception {
        LazyMan instance1 = LazyMan.getInstance();
        //获取类构造器
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        //无视构造器私有
        constructor.setAccessible(true);
        //创建一个新对象
        LazyMan instance2 = constructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);
    }
}

结果

Exception in thread "main" java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at LazyMan.main(LazyMan.java:38)
Caused by: java.lang.RuntimeException: 不要靠反射创建实例对象
	at LazyMan.<init>(LazyMan.java:13)
	... 5 more

● 攻方:不直接创建对象,全靠反射创建对象

    public static void main(String[] args) throws Exception {
   
        //LazyMan instance1 = LazyMan.getInstance();
        //获取类构造器
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        //无视构造器私有
        constructor.setAccessible(true);
        //创建一个新对象
        LazyMan instance1 = constructor.newInstance();
        LazyMan instance2 = constructor.newInstance();
        System.out.println(instance1);
        System.out.println(instance2);
    }

结果

LazyMan@1b6d3586
LazyMan@4554617c

● 守方:设置一个红绿灯来当作标志

public class LazyMan {
	//标记
    private static boolean flag = true;
	//还是有漏洞,这个字段有可能被反编译获取到字段名,然后进行修改
    private LazyMan(){
        synchronized (LazyMan.class){
            if(flag){
                flag = false;
            }else {
                throw new RuntimeException("不要靠反射创建实例对象");
            }
        }
    }

    private volatile static LazyMan LAZYMAN;

    public static LazyMan getInstance(){
        if (LAZYMAN==null){
            synchronized (LazyMan.class){
                if (LAZYMAN==null){
                    LAZYMAN = new LazyMan();
                }
            }
        }
        return LAZYMAN;
    }

    public static void main(String[] args) throws Exception {
        //不直接创建对象,全靠反射创建对象
        //LazyMan instance1 = LazyMan.getInstance();
        //获取类构造器
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        //无视构造器私有
        constructor.setAccessible(true);
        //创建一个新对象
        LazyMan instance1 = constructor.newInstance();
        LazyMan instance2 = constructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);
    }
}

● 攻方:通过反编译手段获取到标志字段名,再修改它的值

    public static void main(String[] args) throws Exception {
        //不直接创建对象,全靠反射创建对象
        //LazyMan instance1 = LazyMan.getInstance();
        //通过反编译手段获取到字段名,再通过反射获取该字段
        Field flag = LazyMan.class.getDeclaredField("flag");
        //无视字段私有
        flag.setAccessible(true);
        //获取类构造器
        Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
        //无视构造器私有
        constructor.setAccessible(true);
        //创建一个新对象
        LazyMan instance1 = constructor.newInstance();

        //创建完对象之后,更改flag的值
        flag.set(instance1,true);

        LazyMan instance2 = constructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);
    }

结果

LazyMan@4554617c
LazyMan@74a14482

所谓道高一尺,魔高一丈就是这样吧。

问题来了,如何解决这个万恶之源呢,构造器创建实例,那看看创建实例的方法newInstance()

    @CallerSensitive
    public T newInstance(Object ... initargs)
        throws InstantiationException, IllegalAccessException,
               IllegalArgumentException, InvocationTargetException
    {
        if (!override) {
            if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                Class<?> caller = Reflection.getCallerClass();
                checkAccess(caller, clazz, null, modifiers);
            }
        }
        //从这个方法内可得知,当这个类是一个枚举类的时候,会被告知不能通过反射创建枚举对象
        if ((clazz.getModifiers() & Modifier.ENUM) != 0)
            throw new IllegalArgumentException("Cannot reflectively create enum objects");
        ConstructorAccessor ca = constructorAccessor;   // read volatile
        if (ca == null) {
            ca = acquireConstructorAccessor();
        }
        @SuppressWarnings("unchecked")
        T inst = (T) ca.newInstance(initargs);
        return inst;
    }

● 使用枚举类实现单例模式

public enum EnumSingle {

    INSTANCE;

    public EnumSingle getInstance(){
        return INSTANCE;
    }

}
class test{
    public static void main(String[] args) {
        EnumSingle instance1 = EnumSingle.INSTANCE;
        EnumSingle instance2 = EnumSingle.INSTANCE;

        System.out.println(instance1);
        System.out.println(instance2);
    }
}

结果

INSTANCE
INSTANCE

● 尝试破坏枚举类的单例模式

class test{
    public static void main(String[] args) throws Exception {
        EnumSingle instance1 = EnumSingle.INSTANCE;
        EnumSingle instance2 = EnumSingle.INSTANCE;

        Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        EnumSingle instance3 = declaredConstructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);
        
        System.out.println(instance3);
    }
}

结果

Exception in thread "main" java.lang.NoSuchMethodException: EnumSingle.<init>()
	at java.lang.Class.getConstructor0(Class.java:3082)
	at java.lang.Class.getDeclaredConstructor(Class.java:2178)
	at test.main(EnumSingle.java:17)
    //被告知这个枚举类里没有这个方法(空参构造器)

继续深挖,查看源码class文件,可以发现它确实是有空参构造器的

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

public enum EnumSingle {
    INSTANCE;

    private EnumSingle() {
    }

    public EnumSingle getInstance() {
        return INSTANCE;
    }
}

最终结果不会骗人,那就可能是class文件骗人,尝试反编译下class文件,发现这个类的细节更加清晰了,但是还是表明其存在空参构造器

D:\NEW\out\production\Singleton>javap -p EnumSingle.class
Compiled from "EnumSingle.java"
public final class EnumSingle extends java.lang.Enum<EnumSingle> {
  public static final EnumSingle INSTANCE;
  private static final EnumSingle[] $VALUES;
  public static EnumSingle[] values();
  public static EnumSingle valueOf(java.lang.String);
  private EnumSingle();
  public EnumSingle getInstance();
  static {};
}

连java自带的工具都整不明白了,那就使用专业的工具jad试试

D:\NEW\out\production\Singleton>jad -sjava EnumSingle.class
Parsing EnumSingle.class... Generating EnumSingle.java

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   EnumSingle.java
public final class EnumSingle extends Enum
{

    public static EnumSingle[] values()
    {
        return (EnumSingle[])$VALUES.clone();
    }

    public static EnumSingle valueOf(String name)
    {
        return (EnumSingle)Enum.valueOf(EnumSingle, name);
    }
	//生成了最终的类文件,发现这个类并不存在空参构造器,只有一个有参构造器
    private EnumSingle(String s, int i)
    {
        super(s, i);
    }

    public EnumSingle getInstance()
    {
        return INSTANCE;
    }

    public static final EnumSingle INSTANCE;
    private static final EnumSingle $VALUES[];

    static 
    {
        INSTANCE = new EnumSingle("INSTANCE", 0);
        $VALUES = (new EnumSingle[] {
            INSTANCE
        });
    }
}

利用这个有参构造器再来试试反射

public class Test {
    public static void main(String[] args) throws Exception {

        EnumSingle instance1 = EnumSingle.INSTANCE;
        EnumSingle instance2 = EnumSingle.INSTANCE;

        Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
        declaredConstructor.setAccessible(true);
        EnumSingle instance3 = declaredConstructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);

        System.out.println(instance3);
    }
}

结果

Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects
	at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
	at Test.main(Test.java:12)

终于出现了源码里的那一段 Cannot reflectively create enum objects

● 到此为止,单例模式就结束了,可以看出,反射是真的强大,下一步要破坏单例模式,得从实例方法源码入手了…

工厂模式

实例化对象不使用new,创建者和调用者分离

简单工厂模式

创建一个工厂,所有的实例化都从这个工厂拿
优点:方便
缺点:不满足开闭原则

工厂方法模式

创建一个总的工厂接口,再创建一个类的接口,后面创建类时都去实现类接口,创建工厂时都去实现工厂接口
优点:满足了开闭原则
缺点:不如简单工厂模式方便,创建、维护较之复杂

抽象工厂模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值