JAVA基础-加油站付款模块final单例类enum类

加油站付款模块

image

final

image

单例类

1.饿汉式单例

1)私有化类2)建立私有化静态变量对象 3)通过方法返回对象

饿汉式单例

    //1.私有化类
    private ehaninstance(){

    }
    //2.创建对象
    private static ehaninstance ehan = new ehaninstance();

    //3.返回对象
    public static ehaninstance getEhan() {
        return ehan;
    }

2.懒汉式单例

1)私有化类 2)建立私有化静态变量但不创建对象 3)通过方法返回并创建对象

懒汉式单例
    //1.私有化类
    private lanhaninstance(){

    }
    //2.私有化静态变量
    private static lanhaninstance a;
    //3.提供静态方法返回对象:在第一次调用时创建对象
    public static lanhaninstance getlanhan(){
        if(a == null){
            a = new lanhaninstance();
        }
        return a;
    }

enum枚举类

image

image

枚举类应用
package enumdemo;

public enum a {
    up,down,left,right;
}
public class test {
    //枚举类测试
    public static void main(String[] args) {
        move(a.up);
    }
    public static void move(a dir){

        switch (dir){
            case up :
                System.out.println("向上移动");
                break;
            case down:
                System.out.println("向下移动");
                break;
            case right:
                System.out.println("向右移动");
                break;
            case left:
                System.out.println("向左移动");
                break;

        }
    }
}

posted @ 2025-07-14 20:48  柳成荫y  阅读(11)  评论(0)    收藏  举报