package com.model.danli; import java.util.ArrayList; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/7/2 16:40 * 单例模式:饿汉式,懒汉式 */ public class DanLiMoShiDemo01 { public static void main(String[] args) { GirlFriend girlFriend = GirlFriend.getGirlFriend(); GirlFriend girlFriend1 = GirlFriend.getGirlFriend(); System.out.println(girlFriend1 == girlFriend); GirlFriend02 girlFriend02 = GirlFriend02.getGirlFriend02(); GirlFriend02 girlFriend03 = GirlFriend02.getGirlFriend02(); System.out.println(girlFriend03==girlFriend02); } } //饿汉式 class GirlFriend{ private String name; private int age; /** * 1.构造器私有化 * 2.在类的内部直接创建对象 * 3.提供一个公共的static的方法,返回类的对象 * 在类加载的时候创建单例模式对象 * */ private static GirlFriend girlFriend=new GirlFriend(); private GirlFriend() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static GirlFriend getGirlFriend() { return girlFriend; } @Override public String toString() { return "GirlFriend{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } } class GirlFriend02{ /** * 1.构造器私有化 * 2.定义一个static修斯的类对象 * 3.提供一个static修饰的public方法,返回这个类对象 * 4.提供的public方法,判断是否已经创建过对象,如果创建过就返回上次创建的类对象,从而保证单例模式 * */ private String name; private int age; private static GirlFriend02 girlFriend02; private GirlFriend02(){ } public static GirlFriend02 getGirlFriend02(){ if (girlFriend02==null){ synchronized (GirlFriend02.class){ if (girlFriend02==null){ girlFriend02=new GirlFriend02(); } } } return girlFriend02; } // 单例线程模式下可以,多线程时无法保证单例 // public static GirlFriend02 getGirlFriend02(){ // if (girlFriend02==null){ // girlFriend02=new GirlFriend02(); // } // return girlFriend02; // } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "GirlFriend02{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
原文:https://www.cnblogs.com/zzhAylm/p/14964172.html