四、java枚举

    xiaoxiao2021-03-25  143

    一、枚举说明:结果是可以穷举的

    枚举类:枚举类的对象是有限个,可以穷举出来。所以需要私有化构造函数。

    二、枚举类的创建示例

    /** * A、私有化构造函数; * B、创建这个类的常量属性(一定是常量,final修饰) * C、通过构造函数给这些属性赋值,并提供get操作 * D、创建枚举对象(放在枚举类的第一行):public static final 类名 常量名=new * 构造函数(实参);以分号结束,没有enum关键词修饰类的时候。 * 简写:常量名1(实参),常量名2(实参),常量名3(实参);(enum关键词的类) */ public enum EnumTest { RED("red"), GREEN("green"), YELLOW("yellow"); private String color; private EnumTest(String color) { this.color = color; } // get/set for color public String getColor() { return color; } } 三、以枚举引出单例模式

    class SingletonClass {//饿汉式 // 声明静态对象 private static SingletonClass instance = new SingletonClass(); // 私有化构造函数 private SingletonClass() {} // 设置当前类对象的静态访问方法 public static SingletonClass getInstance() { return instance; } public void say() { System.out.println("hello this is 饿汉式 a singleton!"); } } class SingletonClassLan {//懒汉式暂时存在线程安全问题 // 声明静态对象 private static SingletonClassLan instance;// = new SingletonClassLan(); // 私有化构造函数 private SingletonClassLan() {} // 设置当前类对象的静态访问方法//通过synchronized(同步)处理懒汉式单例设计模式存在的线程安全问题。 //synchronized保证了线程安全,但是降低了效率。 public static synchronized SingletonClassLan getInstance() { //instance = new SingletonClassLan(); if(instance == null){//通过if判断来避免多次调用构造函数产生不同对象。 instance = new SingletonClassLan(); } return instance; } public void say() { System.out.println("hello this is a 懒汉式 singleton!"); } }

    转载请注明原文地址: https://ju.6miu.com/read-9361.html

    最新回复(0)