zoukankan      html  css  js  c++  java
  • 设计模式之单例模式

    单例模式的一种实现

    将类的所有构造方法都设为private让其无法从外部实例化,然后再内部来实例化一个类,提供一个get方法获取。

     1 public class Student {
     2     private String name;
     3     private String id;
     4 
     5     public String getName() {
     6         return name;
     7     }
     8 
     9     public void setName(String name) {
    10         this.name = name;
    11     }
    12 
    13     public String getId() {
    14         return id;
    15     }
    16 
    17     public void setId(String id) {
    18         this.id = id;
    19     }
    20 
    21     private Student(String name, String id) {
    22         this.name = name;
    23         this.id = id;
    24     }
    25 
    26     private Student() {
    27     }
    28 
    29     @Override
    30     public String toString() {
    31         return "Student [name=" + name + ", id=" + id + "]";
    32     }
    33 
    34     private static Student instance = null;
    35 
    36     public static Student getInstance() {//判断是否存在实例
    37         if (instance == null)
    38             instance = new Student();
    39         return instance;
    40     }
    41 }

    测试:

    1 Student student1 = Student.getInstance();//先获取一个学生对象
    2 student1.setId("9527");
    3 student1.setName("华安");
    4 Student student2 = Student.getInstance();//再获取学一个学生对象
    5 System.out.println(student1==student2);
    6 System.out.println(student2);
  • 相关阅读:
    [HDU 4828] Grids
    约瑟夫问题合集
    [POJ 1365] Prime Land
    [POJ 3270] Cow Sorting
    [POJ 1674] Sorting by Swapping
    SGU 188.Factory guard
    POJ 2942.Knights of the Round Table (双连通)
    POJ 1236.Network of Schools (强连通)
    POJ 2186.Popular Cows (强连通)
    POJ 1734.Sightseeing trip (Floyd 最小环)
  • 原文地址:https://www.cnblogs.com/lingdu9527/p/11006195.html
Copyright © 2011-2022 走看看