Java---单例、多例设计模式

单例和多例的设计模式特点就是构造方法被私有化,外部无法直接用“new”实例化。只能通过调用类内部提供的静态方法取得实例。

单例设计模式:
饿汉式单例设计模式
class Singleton{
    private Singleton(){}
    //定义全局常量的时候直接实例化
    private static final Singleton INSTANCE = new Singleton();
    public static Singleton getSingleton(){
        return INSTANCE;
    }
    public void print(){
        System.out.println("输出");
    }
}
public class Test {
    public static void main(String[] args) {
        Singleton s = Singleton.getSingleton();
        s.print();
    }

}

懒汉式单例设计模式

class Singleton{
    private Singleton(){}
    private static  Singleton INSTANCE =null;
    public static Singleton getSingleton(){
        if(INSTANCE ==null){ //在调用的时候再实例化
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }
    public void print(){
        System.out.println("输出");
    }
}
public class Test {
    public static void main(String[] args) {
        Singleton s = Singleton.getSingleton();
        s.print();
    }

}

饿汉单例设计模式:不管有没有调用,都已经实例化。
懒汉单例设计模式:当被调用的时候,再进行实例化。


多例设计模式
单例和多例的区别是,单例只提供一个实例化对象,而多例会存在多个实例化对象,例如性别只提供两个实例,星期只提供七个实例。

class Color { 
    private static final Color RED = new Color("红色") ; 
    private static final Color GREEN = new Color("绿色") ; 
    private static final Color BLUE = new Color("蓝色") ;
    private String title ; 
    private Color(String title) { 
        this.title = title ; 
    }
    public String toString() { 
        return this.title ;
    }
    public static Color getColor(String colors) { 
        switch (colors) { 
            case "red" : return RED ; 
            case "green" : return GREEN ;
            case "blue" : return BLUE ;
            default : return null ;
        }
    }
}
public class TestDemo { 
    public static void main(String args[]) {
        Color red = Color.getColor("red") ; 
        System.out.println(red) ;   
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值