栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java的第九次学习

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
    }
}

总结

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/854801.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号