设计模式(一)

1 设计模式

什么是设计模式?

一个问题通常由n种解法,其中肯定有一种解法是最优的,这个最优的解法被人总结出来了,称之为设计模式

设计模式有20多种,对应20多种软件开发中会遇到的问题。

关于设计模式的学习,主要学什么?

1)解决什么问题?

2)怎么写?

2 单例设计模式

简介:确保一个类只有一个对象;

类别:1)饿汉式单例:拿对象时,对象早就创建好了;

         2)懒汉式单例:拿对象时,才开始创建对象

写法:1)把类的构造器私有;

         2)定义一个类变量记住类的一个对象;

         3)定义一个类方法,返回对象

应用场景和好处:任务管理器、源码Runtime类

复制代码
/**
 * 饿汉式单例设计模式
 */
public class SingleInstanceHungry {

    /**
     * 2 定义一个类变量记住类的一个对象
     **/
    private static SingleInstanceHungry singleInstanceHungry = new SingleInstanceHungry();

    /**
     * 1 把类的构造器私有化
     **/
    private SingleInstanceHungry(){ }

    /**
     * 3 定义一个类方法,返回对象
     **/
    public static SingleInstanceHungry getInstance(){
        return singleInstanceHungry;
    }
}

/** * 懒汉式单例设计模式 */ public class SingleInstanceLazy { /** * 2 定义一个类变量,用于存储这个类的一个对象 **/ private static SingleInstanceLazy singleInstanceLazy; /** * 1 把类的构造器私有化 **/ private SingleInstanceLazy() { } /** * 3 定义一个类方法,这个方法要保证第一次调用时才创建一个对象,后面调用时都会用这同一个对象返回 **/ public static SingleInstanceLazy getInstance() { if (singleInstanceLazy == null) { singleInstanceLazy = new SingleInstanceLazy(); } return singleInstanceLazy; } } import single.SingleInstanceHungry; import single.SingleInstanceLazy; public class DesignPatternsTest { public static void main(String[] args) { SingleInstanceHungry singleInstanceHungry1 = SingleInstanceHungry.getInstance(); SingleInstanceHungry singleInstanceHungry2 = SingleInstanceHungry.getInstance(); System.out.println(singleInstanceHungry1); System.out.println(singleInstanceHungry2); SingleInstanceLazy singleInstanceLazy1 = SingleInstanceLazy.getInstance(); SingleInstanceLazy singleInstanceLazy2 = SingleInstanceLazy.getInstance(); System.out.println(singleInstanceLazy1); System.out.println(singleInstanceLazy2); } }
复制代码
posted @   DAYTOY-105  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示

目录导航