设计模式的概念:设计模式是在大量的实践中总结和理论化之后优选的代码结构、编程风格、以及解决问题的思考方式。一共有23种设计模式。
单例模式:
1、解决的问题:使得一个类只能够创建一个对象。
2、如何实现?(饿汉式)
(懒汉式)2.1私有化构造器,使得在类的外部不能够调用此构造器。
2.2在类的内部创建一个实例。
2.3私有化此对象,通过公共的方法来调用。
2.4此公共方法只能通过类来调用,因此设置为static类型的,同时类的实例也应是static的。
public class Singleton { private Singleton() { } private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } }
1.私有化构造器
2.创建static类的实例,私有化并将该实力对象设置为null。
3.提供公共static的方法来创建并返回实例。
public class Singleton2 { private Singleton2() { } private static Singleton2 instance = null; public static Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; } }