单例模式 singleton;
2017-01-07 09:19
471 查看
单例模式 singleton——一个人只能养一只猫
class Cat { String name; //通过给构造方法加上private,使得只能在Cat类内部生成Cat对象 private Cat(String name) { this.name = name; } //我只生成一个猫对象名叫旺财,所以也就是单例 static Cat c = new Cat("旺财"); //通过加上static使得可以通过类名来直接调用这个方法,得到Cat对象 static Cat getCat() { return c; } }
public class Person { String name; Cat c; Person(String name) { this.name = name; } public String toString() { return name+"养了一只猫名叫"+c.name; } public static void main(String[] args) { Person father = new Person("张三"); father.c = Cat.getCat(); //养第二只猫出现错误,因为这是不允许的,Cat的构造方法是private的,所以在Cat类外访问不到其构造方法,新生成不了对象 //Cat a = new Cat("旺丁"); System.out.println(father); } }
测试结果:
相关文章推荐
- Singleton模式之Delphi实现
- 设计模式入门(1)------单件(Singleton)
- 设计模式之Singleton(单态)
- VB.NET实现Singleton模式
- 单例(Singleton)模式
- 设计模式之Singleton(单态)
- PHP单子模式(SINGLETON)的简单实现
- Singleton模式
- 静态方法 &singleton模式--(摘抄csdn论坛,作者:hhhh63(hhhh63))
- singleton模式的一种变体:double-checked locking
- C++设计模式:Singleton的模板实现之一
- singleton设计模式的C#实现(上)
- 设计模式之-----单件(singleton)
- 设计模式(4)-单例模式(Singleton)
- 设计模式、用Delphi实现---->Singleton 模式
- 从C#的Singleton设计模式实现看.NET Framework特性对开发者的重要性
- Singleton模式的C++实现研究(转贴)
- singleton design pattern----------创建型模式之一
- 设计模式之Singleton(单态)
- Singleton模式的C++实现研究(转载)