单例模式
Posted 奋斗的少年WH
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
1 package danlimoshi; 2 3 public class FactoryTest { 4 public static void main(String[] args) { 5 Factory factory=Factory.getFactory(); 6 System.out.println("factory "+factory); 7 Factory factory2=Factory.getFactory(); 8 factory2.setFactory("张三", 20); 9 System.out.println("factory2 "+factory2+"factory "+factory); 10 System.out.println(factory==factory2); 11 } 12 } 13 14 class Factory { 15 private static Factory factory = new Factory(); 16 private static String name="单例模式"; 17 private static int age=18; 18 private Factory(){}; 19 20 static Factory getFactory() { 21 return factory; 22 } 23 24 static void setFactory(String name,int age) { 25 Factory.name=name; 26 Factory.age=age; 27 } 28 29 @Override 30 public String toString() { 31 return "Factory [name="+name+", age="+age+"]"; 32 } 33 34 35 }
1 factory Factory [name=单例模式, age=18] 2 factory2 Factory [name=张三, age=20]factory Factory [name=张三, age=20] 3 true
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章