Java学习笔记 —— 12
2014-11-04 16:41
253 查看
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; } }
相关文章推荐
- 传智博客学习笔记12--JAVA IO
- Effective Java 学习笔记 (12)
- java学习笔记12--国际化
- Java学习笔记_12_File的建立和存储
- java个人学习笔记12(多态)
- 09 12 07 Java web 学习笔记
- java学习笔记12--国际化
- 黑马程序员_JAVA 学习笔记25 WEB篇12
- 【Java学习笔记】基础知识学习12【Set接口的实现类】
- 黑马程序员_学习笔记:12) 其他API:java.lang.Runtime、java.util.Math、java.util.Date、java.util. Calendar
- 09 12 15 JavaWeb 学习笔记
- Java 学习笔记12:Java Json对象转换
- java 设计模式学习笔记(12) - 观察者模式
- 黑马程序员—12—java基础:有关字符串的学习笔记和学习心得体会
- Java学习笔记12
- Effective Java 学习笔记 (12)
- Java与Flex学习笔记(12)----用CSS控制页面样式
- java学习笔记12———网络编程
- JAVA学习笔记(12)关于正则表达式
- 黑马程序言 Java基础学习笔记12 线程的创建