zoukankan      html  css  js  c++  java
  • 单例模式(Singleton Pattern)

    情景:只有一个皇帝(Emperor),三个臣子(Minister)向一个皇帝汇报。

    public class Emperor 
    {
    private static final Emperor emperor = new Emperor();

    private Emperor()
    {

    }

    public static Emperor getInstance()
    {
    return emperor;
    }

    public static void say()
    {
    System.out.println("我是皇帝A");
    }
    }
    public class Minister 
    {

    public static void main(String[] args)
    {
    for(int n=0; n<3; n++)
    {
    Emperor emperor = Emperor.getInstance();
    emperor.say();
    }
    }
    }

    扩展情况:

    有三个皇帝,大臣可以像其中一个皇帝汇报

    import java.util.ArrayList;
    import java.util.Random;


    public class Emperor
    {
    private static int maxNumOfEmperor = 2;
    private static ArrayList<String> nameList = new ArrayList<String>();
    private static ArrayList<Emperor> emperorList = new ArrayList<Emperor>();

    private static int countNumOfEmperor = 0;

    static
    {
    for(int n=0; n<maxNumOfEmperor; n++)
    {
    emperorList.add(new Emperor("皇" + (n + 1)));
    }
    }

    private Emperor()
    {

    }

    private Emperor(String name)
    {
    nameList.add(name);
    }

    public static Emperor getInstance()
    {
    Random random = new Random();

    countNumOfEmperor = random.nextInt(maxNumOfEmperor);

    return emperorList.get(countNumOfEmperor);
    }

    public static void say()
    {
    System.out.println(nameList.get(countNumOfEmperor));
    }
    }
    public class Minister 
    {

    public static void main(String[] args)
    {
    int ministerNum = 5;

    for(int n=0; n<ministerNum; n++)
    {
    Emperor emperor = Emperor.getInstance();

    emperor.say();
    }
    }

    }





  • 相关阅读:
    【强烈推荐】 超漂亮的仿腾讯弹出层效果(兼容主流浏览器<转>;
    必须掌握的八个【cmd 命令行】
    grep命令的用法
    sed 命令的用法1
    Paste命令的用法
    uniq命令的用法
    join命令的用法
    Sort命令的用法
    cut命令的用法
    tr命令学习
  • 原文地址:https://www.cnblogs.com/xiaobo68688/p/2367164.html
Copyright © 2011-2022 走看看