Java学习笔记 —— 12

来源:互联网 发布:家庭网络拓扑图 nas 编辑:程序博客网 时间:2024/06/02 02:06



23种设计模式


单例的设计模式:

饿汉式

1、解决的问题:使一个类只能够创建一个对象。

2、如何实现。如下:

public class TestSingleton {public static void main(String[] args) {Singleton s1 = Singleton.getInstance();Singleton s2 = Singleton.getInstance();System.out.println(s1 == s2);}}//只能创建Singleton的单个实例class Singleton {//1、私有化构造器:使得在类的外部不能使用此构造器private Singleton() {super();// TODO Auto-generated constructor stub}//2、在类的内部创建一个类的实例private static Singleton instance = new Singleton();//3、私有化此对象,通过公共的方法调用//4、此公共地方法,只能通过类来调用,因为数组为static的,同时类的实例也必须为static声明的。public static Singleton getInstance() {return instance;}}

懒汉式

//存在线程安全问题。class Singleton1 {//1、私有化构造器:使得在类的外部不能使用此构造器private Singleton1() {super();// TODO Auto-generated constructor stub}//2、在类的内部创建一个类的实例private static Singleton1 instance = null;//3、public static Singleton1 getInstance() {if (instance == null) {instance = new Singleton1();}return instance;}}






0 0