设计模式-模板方法模式(Template Method)

模板方法-设计模式(Template Method)

  • 设计模式基础知识
    • 基础概念
      . . . .简而言之,就是套路二字.是一套反复被使用,多数人知晓的,经过分类编目,代码设计经验的总结.对待不同情况,可以使用的最优解.还是古人云的好啊 .
      . . . .自古深情留不住,唯有套路得人心!
    • 作用
      . . . . 实用设计模式不仅仅可以提高代码重用度,代码更容易理解,保证代码的可靠性.
    • 使用场景
      . . . . 工具类,配置文件,线程池,缓存,日志等
  • 单例设计模式—饿汉式
    • 代码参考
    public class Singleton {
        //1.将构造方法私有化,不允许外部直接创建对象
        private Singleton() {
        }
        //2.创建类的唯一实例 ,其实只用加一个static即可,对象只会有一个了.静态修饰符修饰的变量只会随着类的加载而加载.类只回加载一次.
        private static Singleton instance = new Singleton();
        //3.提供一个用于获取实例的方法
        public static Singleton getInstance(){
            // do filter
            return instance;
        }
    }
    
  • 单例设计模式—懒汉式
    • 代码参考
    public class SingletonLazy {
        //1.将构造方法私有化,不允许外部直接创建对象
        private SingletonLazy() {
        }
        //2.类变量会随着类的加载而初始化为null,用到的时候再new 对象,并将对象地址赋值给私有静态变量.
        private static SingletonLazy instance;
        //3.提供一个用于获取实例的方法
        public static SingletonLazy getInstance(){
            // do filter
            if(instance == null){
                instance = new SingletonLazy();
            }
            return instance;
        }
    }
    
  • 单例设计模式—测试
    • 代码参考
    public class SingletonTest {
    	// 比对对象地址是否相等
        public static void main(String[] args) {
            Singleton s0 = Singleton.getInstance();
            Singleton s1 = Singleton.getInstance();
            System.out.println(s0);
            System.out.println(s1);
    
            System.out.println("-------------------------");
    
            SingletonLazy s2 = SingletonLazy.getInstance();
            SingletonLazy s3 = SingletonLazy.getInstance();
            System.out.println(s2);
            System.out.println(s3);
        }
    
    }
    
  • 单例设计模式—总结
    • 饿汉式,是加载类时比较慢,但运行时获取的对象速度比较快,线程安全.
    • 懒汉式加载类时比较快,但运行获取对象的速度比较慢,线程不安全
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值