/* * 设计模式之单例模式的简单demo */ class Single { /* * 创建一个本类对象。 * 和get/set方法思想一样,类不能直接调用对象 * 所以用private限制权限 */ private static Single s = new Single(); /* * 构造函数私有化目的是为了只能产生一个对象 */ private Single(){} // 定义一个方法返回该对象,让外部可以调用。 public static Single getInstance() { return s; } } class SingleDemo { public static void main(String[] args) { // Single s = Single.s; Single s1 = Single.getInstance(); Single s2 = Single.getInstance(); System.out.println(s1 == s2); } }
/* * 单例模式之饿汉式与懒汉式 */ //饿汉式 class Single { private static Single s = new Single(); private Single(){} public static Single getInstance() { return s; } } //懒汉式 class Single { private static Single s = null; private Single(){} public static Single getInstance() { if (s == null) { s = new Single(); } return s; } }
/* * 单例模式的小例子 */ class SuperMan { private String name; private static SuperMan man = new SuperMan("Clarke"); private SuperMan (String name) { this.name = name; } public static SuperMan getInstance () { return man; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } } class SuperManDemo { public static void main(String[] args) { SuperMan s1 = SuperMan.getInstance(); String name1 = s1.getName(); System.out.println("name1 = " + name1); SuperMan s2 = SuperMan.getInstance(); s2.setName("hero"); String name2 = s2.getName(); System.out.println("name2 = " + name2); } }