首页 > 代码库 > 单例模式

单例模式

 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     @Override30     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

 

单例模式