创建型模式-单例模式-工厂模式

处理资源访问冲突,表示全局唯一类

//饿汉式 public class Hungry { private static final Hungry hungry = new Hungry(); private Hungry(){} public Hungry getInstance(){ return hungry; } } //懒汉式 public class Lazy { private static Lazy lazy = null; public Lazy getInstance(){ if (lazy == null){ lazy = new Lazy(); return lazy; } else return lazy; } } //双重检测 public class DoubleLock { private static DoubleLock doublelock = null; private DoubleLock(){}; public DoubleLock getInstance(){ if (doublelock == null) { synchronized (DoubleLock.class){ if (doublelock == null) { doublelock = new DoubleLock(); return doublelock; } } } return doublelock; } } //静态内部类 public class InnerClass { private InnerClass(){ if (LazyInnerClass.innerClass != null){ throw new RuntimeException("不能使用私有构造器创建新的实例"); } } public InnerClass getInstance(){ return LazyInnerClass.innerClass; } private static class LazyInnerClass{ private static final InnerClass innerClass = new InnerClass(); } } //枚举 public enum EnumSingle { INSTANCE; public static EnumSingle getInstance(){ return INSTANCE; } }

从业务概念上,有些数据在系统中只应该保存一份,就比较适合设计为单例类。比如,系统的配置信息类。除此之外,我们还可以使用单例解决资源访问冲突的问题。

JDK中Runtime类就是使用的饿汉式加载,运行时的状态在当前状态就只有一份。

java.awt.Desktop中的getDesktop()获取你的桌面,使用的是懒汉式加载。

工厂模式

当我们需要创建很多对象的时候可以使用工厂方法,利用工厂来创建对象从而隐藏创建的细节,并且通过new工厂接口实现对应需要创建对象的子类工厂可以创建不同的对象并且容易扩展工厂

public interface Book { public String getName(); public String getAuth(); public Double getPrice(); } public class JavaBook implements Book { private String name; private String auth; private Double price; public JavaBook(String name, String auth, Double price) { this.name = name; this.auth = auth; this.price = price; } public String getName() { return this.name; } public String getAuth() { return this.auth; } public Double getPrice() { return this.price; } }

使用工厂模式创建

public interface BookFactory { Book Create(); } public class JavaBookFactory implements BookFactory { @Override public Book Create() { return new JavaBook("1","2",3.0); } } public class Test { public static void main(String[] args) { BookFactory bookFactory = new JavaBookFactory(); JavaBook create = (JavaBook)bookFactory.Create(); System.out.println(create.getAuth()); } }

Java源码中的Calender

private static Calendar createCalendar(TimeZone zone, Locale aLocale) { CalendarProvider provider = LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale) .getCalendarProvider(); if (provider != null) { try { return provider.getInstance(zone, aLocale); } catch (IllegalArgumentException iae) { // fall back to the default instantiation } }

应用场景:

JDK中Calendar的getlnstance方法

JDBC中的Connection对象的获取

Spring中IOC容器创建管理bean对象

反射中Class对象的newlnstance方法

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwwgjf.html