文章目录
- 前言
- 简介
- 单例模式
- 模板模式
- 总结
前言
简介
什么是设计模式?
设计模式是在大量的实践中总结和理 论化之后优选的代码结构、编程风格、以及解决问题的思考方式。设计模式就像是经典的棋谱,不同的棋局,我们用不同的棋谱,免去我们自己再思考和摸索。
单例模式
1、什么是单例模式?
单例(单个的实例)
1.所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某 个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法
2.单例模式有两种方式: 1)饿汉式2)懒汉式
2、单例模式应用实例
演示饿汉式和懒汉式单例模式的实现。
步骤如下:
1)构造器私有化=》防止直接new
2)类的内部创建对象
3)向外暴露一个静态的公共方法。
getInstance
4)代码实现
SingleTonO1.java(饿汉式)
/**
* 单例模式-饿汉式
*
* @author 罗汉 QQ;1072344372
* @date 2022/11/30
*/
public class SingleTon01 {
public static void main(String[] args) {
// GirlFriend xh = new GirlFriend("小红");
// GirlFriend xb = new GirlFriend("小白");
//通过方法可以获取对象
GirlFriend instance = GirlFriend.getInstance();
System.out.println(instance);
GirlFriend instance2 = GirlFriend.getInstance();
System.out.println(instance2);
System.out.println(instance == instance2);//T
//System.out.println(GirlFriend.n1);
//...
}
}
//有一个类, GirlFriend
//只能有一个女朋友
class GirlFriend {
private String name;
//public static int n1 = 100;
//为了能够在静态方法中,返回 gf对象,需要将其修饰为static
//對象,通常是重量級的對象, 餓漢式可能造成創建了對象,但是沒有使用.
private static GirlFriend gf = new GirlFriend("小红红");
//如何保障我们只能创建一个 GirlFriend 对象
//步骤[单例模式-饿汉式]
//1. 将构造器私有化
//2. 在类的内部直接创建对象(该对象是static)
//3. 提供一个公共的static方法,返回 gf对象
private GirlFriend(String name) {
System.out.println("構造器被調用.");
this.name = name;
}
public static GirlFriend getInstance() {
return gf;
}
@Override
public String toString() {
return "GirlFriend{" +
"name='" + name + '\'' +
'}';
}
}
SingleTonO2java(懒汉式)
/**
* 演示懒汉式的单例模式
*
* @author 罗汉 QQ;1072344372
* @date 2022/11/30
*/
public class SingleTon02 {
public static void main(String[] args) {
//new Cat("大黄");
//System.out.println(Cat.n1);
Cat instance = Cat.getInstance();
System.out.println(instance);
//再次调用getInstance
Cat instance2 = Cat.getInstance();
System.out.println(instance2);
System.out.println(instance == instance2);//T
}
}
//希望在程序运行过程中,只能创建一个Cat对象
//使用单例模式
class Cat {
private String name;
public static int n1 = 999;
private static Cat cat ; //默认是null
//步骤
//1.仍然构造器私有化
//2.定义一个static静态属性对象
//3.提供一个public的static方法,可以返回一个Cat对象
//4.懒汉式,只有当用户使用getInstance时,才返回cat对象, 后面再次调用时,会返回上次创建的cat对象
// 从而保证了单例
private Cat(String name) {
System.out.println("构造器调用...");
this.name = name;
}
public static Cat getInstance() {
if(cat == null) {//如果还没有创建cat对象
cat = new Cat("小可爱");
}
return cat;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
'}';
}
}
3、饿汉式 VS 懒汉式
两者的区别:
1.二者最主要的区别在于创建对象的时机不同:
饿汉式是在类加载就创建了对象实例, 而懒汉式是在使用时才创建。
2.饿汉式不存在线程安全问题,懒汉式存在线程安全问题。
3.饿汉式存在浪费资源的可能。因为如果程序员一个对象实例都没有使用,那么饿汉式创建的对象就浪费了,懒汉式是使用时才创建,就不存在这个问题。
4.在我们javaSE标准类中,java.lang.Runtime就是经典的单例模式。
模板模式
总结
提示:未完待续