java有23种设计模式(编程思想/编程方式),不要被设计模式固化思想,随心所有与的编写代码
工厂模式 单例模式 代理模式 适配器模式 观察者模式 MVC 模式 等等
工厂模式
就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建
接口
public interface Fruit {
public void print();
}
2个实现类
public class Apple implements Fruit{
@Override
public void print() {
System.out.println("我是一个苹果");
}
}
public class Orange implements Fruit{
@Override
public void print() {
System.out.println("我是一个橘子");
}
}
工厂类
public class FruitFactory {
public Fruit produce(String type){
if(type.equals("apple")){
return new Apple();
}else if(type.equals("orange")){
return new Orange();
}else{
System.out.println("请输入正确的类型!");
return null;
}
}
}
测试类
public class FactoryTest {
public static void main(String[] args) {
FruitFactory factory = new FruitFactory();
Fruit apple = factory.produce("apple");
apple.print();
}
}
单例模式
单例模式是设计模式中最常见也最简单的一种设计模式,保证了在程序中只有一个实例存在
一、作用
单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点
二、适用场景
1. 应用中某个实例对象需要频繁的被访问。
2. 应用中每次启动只会存在一个实例。如账号系统,数据库系统。
三、常用的使用方式
(1)懒汉式
优点:延迟加载(需要的时候才去加载)
缺点: 线程不安全,在多线程中很容易出现不同步的情况
public class Singleton {
/* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
private static Singleton instance = null;
/* 私有构造方法,防止被实例化 */
private Singleton() {
}
/* 1:懒汉式,静态工程方法,创建实例 */
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
(2)饿汉式
优点:线程安全
缺点:类加载时直接创建对象
public class Singleton {
/* 持有私有静态实例,防止被引用 */
private static Singleton instance = new Singleton();
/* 私有构造方法,防止被实例化 */
private Singleton() {
}
/* 1:懒汉式,静态工程方法,创建实例 */
public static Singleton getInstance() {
return instance;
}
}