Java的第九次学习

单例模式与多例模式

单例模式

在类中将类的构造方法利用private封装私有化,这样就无法通过外部关键字new实例化该类对象,然后利用本类中被static修饰的方法调用该类已实例化的对象。
单例模式又分为两种,懒汉式单例设计与饿汉式单例设计。

饿汉式单例设计

其实就是在定义成员属性时直接进行对象的实例化

public class jj {
    public static void main(String[] args) {
        A per = A.setA("h");
        System.out.println(per);
    }
}
class A{
    private static final A b = new A("二");
    private String c;
    private A(String c){
        this.c = c;
    }
    public static A setA(String c){
        return b;
    }
    public String toString(){
        return c;
    }
}

在这里插入图片描述

懒汉式单例设计

与饿汉式单例设计不同,它是在第一次调用函数时对对象实例化

public class jj {
    public static void main(String[] args) {
        A per = A.setA("h");
        System.out.println(per);
    }
}
class A{
    private static A b;
    private String c;
    private A(String c){
        this.c = c;
    }
    public static A setA(String c){
        A b = new A("二");
        return b;
    }
    public String toString(){
        return c;
    }
}

在这里插入图片描述

多例模式

顾名思义,单例模式是针对单个对象,而多例模式自然是多个对象

public class text {
    public static void main(String[] args){
        Color in = Color.getColor("green");
        System.out.println(in);
    }
}
class Color{
    private static final Color RED = new Color("红色");
    private static final Color GREEN = new Color("绿色");
    private static final Color YELLOW = new Color("黄色");
    private String color;
    private Color(String color){this.color = color;};
    public static Color getColor(String color){
        switch (color){
            case "red":
                return RED;
            case "green":
                return GREEN;
            case "yellow":
                return YELLOW;
            default:
                return null;
        }
    }
    public String toString(){
        return color;
    }
}

在这里插入图片描述

总结

通过这次学习对模式有了进一步的了解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值