设计模式
概述
java 中设计模式通常有 23 种,模式可以分成 3 类,创建型、行为型、结构型。
创建型模式
创建模式设计对象的实例化,特点是不让用户代码依赖于对象的创建或排列方式,避免用户直接使用 new 创建对象。
创建型模式有以下 5 个:
结构型模式
结构模式设计如何组合类和对象以形成更大的结构,和类有关的结构模式涉及如何合理使用继承机制,和对象有关的结构模式涉及如何合理的使用对象组合机制。
结构型模式有以下 7 个:
行为型模式
行为型模式涉及怎样合理的设计对象之间的交互通信,以及怎样合理设计和分配对象的职责,让设计富有弹性、易维护、易复用。
行为型模式有以下 11 个:
单例模式
模式定义
单例模式(Singleton)是指确保一个类只有一个实例,而且自行实例化并提供实例的全局访问。是一种对象创建型模式。又名单件模式或单态模式。
单例模式的设计要素
- 一个私有的静态变量,用于存放一个实例,确保只有一个实例。
- 一个私有的构造函数,用于创建实列,确认单例类只能自己创建实例。
- 一个共有的静态函数,用于向外部系统提供这个单例。
单例的 6 种实现及优缺点
1. 懒汉式(线程不安全)
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}- 说明:先不创建实例,使用的时候再创建。
- 优点:延迟了实例化。需要使用该类的时候再创建,节省了系统资源。
- 缺点:线程不安全。多线程环境下,会创建多个实例出来。
2. 饿汉式(线程安全)
public class HungryManStyleSingleton {
private static HungryManStyleSingleton hungryManStyleSingleton = new HungryManStyleSingleton();
private HungryManStyleSingleton() {
}
public static HungryManStyleSingleton getHungryManStyleSingleton() {
return hungryManStyleSingleton;
}
}- 说明:在类加载时,就实例化好对象。
- 优点:线程安全
- 缺点:提前实例化,若系统很久都没有使用这个类的化,会浪费系统资源
3. 懒汉式(线程安全)
public class LazyStyleThreadSafeSingleton {
private static LazyStyleThreadSafeSingleton lazyStyleThreadSafeSingleton;
private LazyStyleThreadSafeSingleton() {
}
public static synchronized LazyStyleThreadSafeSingleton getLazyStyleThreadSafeSingleton() {
if (lazyStyleThreadSafeSingleton == null) {
lazyStyleThreadSafeSingleton = new LazyStyleThreadSafeSingleton();
}
return lazyStyleThreadSafeSingleton;
}
}- 说明:在懒汉式的基础增加了 synchronized,保证创建实例对象时线程安全。
- 优点:延迟实例化,线程安全
- 缺点:每次获取实例对象都要加锁,效率低下。
4. 双重检验锁
public class DoubleCheckLockSingleton {
private static volatile DoubleCheckLockSingleton doubleCheckLockSingleton;
private DoubleCheckLockSingleton() {
}
public static DoubleCheckLockSingleton getDoubleCheckLockSingleton() {
if (doubleCheckLockSingleton == null) {
synchronized (DoubleCheckLockSingleton.class) {
if (doubleCheckLockSingleton == null) {
doubleCheckLockSingleton = new DoubleCheckLockSingleton();
}
}
}
return doubleCheckLockSingleton;
}
}说明:synchronized 保证了线程安全,volatile 禁止指令重排,保证了变量可见性。 优点:延迟实例化,线程安全 缺点:volatile 对性能有一些影响。
5. 静态内部类
public class StaticInnerClassSingleton {
private StaticInnerClassSingleton() {
}
private static class InnerClass {
private static final StaticInnerClassSingleton staticInnerClassSingleton = new StaticInnerClassSingleton();
}
public static StaticInnerClassSingleton getStaticInnerClassSingleton() {
return InnerClass.staticInnerClassSingleton;
}
}说明:加载外部类的时候,不会提前加载内部类。只有在用到内部类时,才会去加载内部类。使用静态常量修饰单例对象,在加载内部类时完成实列化。 优点:延迟实例化,线程安全。
6. 枚举类实现(线程安全)
public enum EnumSingletonEnum {
ENUM_SINGLETON_ENUM;
void doSomeThing() {
//执行业务代码
}
}说明:枚举本身就是一个单例类,获取枚举就是获取一个单例。 优点:线程安全,防止反射和序列化 缺点:提前实例化
简单工厂模式
模式定义
简单工厂模式(Simple Factory)又称为静态工厂模式,它属于创建型模式。在简单工厂模式中,可以根据参数的不同返回不同的类的实例。简单工厂模式专门定义一个类负责创建其他类的实例,被创建的类通常都又共同的父类。
模式结构
简单工厂模式包含三个角色:
- 一个工厂角色
- 一个抽象产品角色
- 多个具体产品角色
代码分析
public class SimpleFactory {
public static void main(String[] args) {
Product product;
product = Factory.create("A");
product.run();
product = Factory.create("B");
product.run();
}
}
interface Product {
void run();
}
class ProductA implements Product {
@Override
public void run() {
System.out.println("productA run");
}
}
class ProductB implements Product {
@Override
public void run() {
System.out.println("productB run");
}
}
class Factory {
public static Product create(String productName) {
if (productName == "A") {
return new ProductA();
} else if (productName == "B") {
return new ProductB();
} else
return null; }
}工厂方法模式
模式定义
工厂方法模式(Factory Method)也称为虚拟构造器模式或者多态工厂模式,它属于类创建型模式。在工厂方法模式中,工厂父类负责定义创建产品对象的公共接口,工厂子类负责生成具体产品的对象,这样做的目的是将产品类的实例化延迟到工厂子类中完成,即通过工厂子类来确定究竟应该实例化哪一个具体产品类。
模式结构
工厂方法模式包含 4 个角色:
- 一个抽象工厂
- 多个具体工厂
- 一个抽象产品
- 多个具体产品
代码分析
public class FactoryMethod {
public static void main(String[] args) {
Factory factory = new FactoryA();
Product product = factory.create();
product.use();
}
}
interface Product {
void use();
}
interface Factory {
Product create();
}
class ProductA implements Product {
@Override
public void use() {
System.out.println("use ProductA");
}
}
class FactoryA implements Factory {
@Override
public Product create() {
return new ProductA();
}
}
class ProductB implements Product {
@Override
public void use() {
System.out.println("use ProductB");
}
}
class FactoryB implements Factory {
@Override
public Product create() {
return new ProductB();
}
}抽象工厂模式
抽象工厂模式引入的两个新概念
- 产品等级结构:产品等级结构即产品的继承机构,如一个抽象类是电视机,其子类有海尔电视机、海信电视机、TCL 电视机。抽象电视机与具体品牌的电视机之间构成了一个产品等级结构,抽象电视机是父类,具体品牌的电视机是子类。
- 产品族:在抽象工厂模式中,产品族是指由同一个工厂创建的,位于不同产品等级结构的一组产品。如海尔电器工厂生产的海尔电视机、海尔冰箱、海尔空调,它们位于不同的产品等级结构中,在同一个海尔工厂中生产出来。
模式定义
抽象工厂模式(Abstract Factory):提供一个创建一系列相关与相互依赖对象的接口,而无须指定它们的具体类。抽象工厂模式又称为 Kit 模式,属于对象创建模式。
模式结构
抽象工厂模式包含的角色:
- 抽象工厂
- 多个具体工厂
- 多个抽象产品
- 多个具体产品
代码分析
public class AbstractFactory {
public static void main(String[] args) {
Factory factory;
ProductA productA;
ProductB productB;
factory = new FactoryX();
productA = factory.createA();
productB = factory.createB();
productA.use();
productB.eat();
factory = new FactoryY();
productA = factory.createA();
productB = factory.createB();
productA.use();
productB.eat();
}
}
interface ProductA {
void use();
}
interface ProductB {
void eat();
}
interface Factory {
ProductA createA();
ProductB createB();
}
class ProductAX implements ProductA {
@Override
public void use() {
System.out.println("user ProductAX");
}
}
class ProductBX implements ProductB {
@Override
public void eat() {
System.out.println("eat ProductBX");
}
}
class FactoryX implements Factory {
@Override
public ProductA createA() {
return new ProductAX();
}
@Override
public ProductB createB() {
return new ProductBX();
}
}
class ProductAY implements ProductA {
@Override
public void use() {
System.out.println("user ProductAY");
}
}
class ProductBY implements ProductB {
@Override
public void eat() {
System.out.println("eat ProductBY");
}
}
class FactoryY implements Factory {
@Override
public ProductA createA() {
return new ProductAY();
}
@Override
public ProductB createB() {
return new ProductBY();
}
}建造者模式
模式定义
建造者模式(Builder)是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一步步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户无需知道内部的具体构建细节。建造者模式属于对象创建型模式,根据中文翻译的不同,建造者模式又可以称为生成器模式。
模式结构
建造者模式包含的角色:
- 抽象建造者
- 具体建造者
- 指挥者
- 产品角色
代码分析
传统的建造者模式
public class TraditionalBuilderPattern {
public static void main(String[] args) {
Director director = new Director();
director.setBuilder(new BuilderX());
Product product = director.getProduct();
product.use();
}
}
class Product {
private String partA;
private String partB;
public void use() {
System.out.println(this);
}
void setPartA(String partA) {
this.partA = partA;
}
void setPartB(String partB) {
this.partB = partB;
}
}
interface Builder {
void buildPartA();
void buildPartB();
Product build();
}
class BuilderX implements Builder {
private Product product;
public BuilderX() {
product = new Product();
}
@Override
public void buildPartA() {
product.setPartA("builderX build part A");
}
@Override
public void buildPartB() {
product.setPartB("builderX build part B");
}
@Override
public Product build() {
return product;
}
}
class Director {
Builder builder;
public void setBuilder(Builder builder) {
this.builder = builder;
}
public Product getProduct() {
builder.buildPartA();
builder.buildPartB();
return builder.build();
}
}java 简化版建造者模式
public class JavaBuilderPattern {
public static void main(String[] args) {
Computer computer = new Computer.Builder()
.mainBoard("ASUS")
.cpu("Intel")
.memory("Kingston")
.build();
computer.use();
}
}
class Computer {
private String mainBoard;
private String cpu;
private String memory;
private Computer() {
}
public String getMainBoard() {
return mainBoard;
}
public void setMainBoard(String mainBoard) {
this.mainBoard = mainBoard;
}
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getMemory() {
return memory;
}
public void setMemory(String memory) {
this.memory = memory;
}
public void use() {
System.out.println(this);
}
public static class Builder {
private Computer computer;
public Builder() {
computer = new Computer();
}
public Builder mainBoard(String mainBoard) {
computer.setMainBoard(mainBoard);
return this; }
public Builder cpu(String cpu) {
computer.setCpu(cpu);
return this; }
public Builder memory(String memory) {
computer.setMemory(memory);
return this; }
public Computer build() {
return computer;
}
}
}原型模式
模式定义
原型模式(Prototype):用一个已经创建好的对象作为原型,通过复制该原型对象创建一个和原型对象相同的新对象。当直接创建一个新对象的代价比较大时,则采用这种模式。原型模式属于对象创建型模式。
模式结构
角色
- PrototypeObject:原型对象
代码分析
浅拷贝的原型模式
public class ShallowClonePrototypePattern {
public static void main(String[] args) throws CloneNotSupportedException {
ShallowCloneObject prototype = new ShallowCloneObject("shallow clone");
ShallowCloneObject newObject = (ShallowCloneObject) prototype.clone();
System.out.println(prototype + " " + prototype.getName());
System.out.println(newObject + " " + newObject.getName());
}
}
class ShallowCloneObject implements Cloneable {
private String name;
public ShallowCloneObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}深拷贝的原型模式
public class DeepClonePrototypePattern {
public static void main(String[] args) {
DeepCloneObject prototype = new DeepCloneObject("deep clone");
DeepCloneObject newObject = (DeepCloneObject) prototype.deepClone();
System.out.println(prototype + " " + prototype.getName());
System.out.println(newObject + " " + newObject.getName());
}
}
class DeepCloneObject implements Serializable, Cloneable {
private String name;
public DeepCloneObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Object deepClone() {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
Object o = ois.readObject();
return o;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}适配器模式
模式定义
适配器模式(Prototype):可以将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器。适配器模式可以作为类结构模式,也可以作为对象结构模式。
模式结构
适配器模式包含的角色:
- Target:目标抽象类
- Adapter:适配器类
- Adaptee:适配者类
- Client:客户类
适配器模式有两种实现方式:
- 类适配器:适配器类同时实现继承目标抽象类和适配者类。实现抽象类的接口,继承适配者类的方法。这种模式下可以重写抽象类或适配者的方法。
- 对象适配器:适配器类实现目标抽象类,适配者对象作为成员属性包含在适配器类中。适配器类在内部调用适配者对象的方法。这种模式下适配器可以把适配者和适配者的子类适配到目标接口。
代码分析
类适配器
public class ClassAdapter {
public static void main(String[] args) {
Target target = new Adapter();
target.use();
}
}
interface Target {
void use();
}
class Adaptee {
void run() {
System.out.println("adaptee run");
}
}
class Adapter extends Adaptee implements Target {
@Override
public void use() {
super.run();
}
}对象适配器
public class ObjectAdapter {
public static void main(String[] args) {
Target target = new Adapter(new Adaptee());
target.use();
}
}
interface Target {
void use();
}
class Adaptee {
void run() {
System.out.println("adaptee run");
}
}
class Adapter implements Target {
Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void use() {
adaptee.run();
}
}组合模式
模式定义
组合模式(Composite):组合模式将对象组合成树形结构以表示“部分-整体”的层次结构,使得客户端可以统一地处理单个对象和组合对象。组合模式是一种对象结构型设计模式。
模式结构
角色
- Componnet:抽象组合
- Composite:具体组合对象
- Leaf:具体叶子对象
代码分析
public class CompositePattern {
public static void main(String[] args) {
Component composite = new Composite();
Component leaf1 = new Leaf("1");
Component leaf2 = new Leaf("2");
Component leaf3 = new Leaf("3");
Component leaf4 = new Leaf("4");
composite.add(leaf1);
composite.add(leaf2);
composite.add(leaf3);
composite.add(leaf4);
composite.operate();
leaf1.add(leaf2);
}
}
interface Component {
void add(Component component);
void remove(Component component);
Component getChild(int index);
void operate();
}
class Composite implements Component {
private List<Component> childs = new ArrayList<Component>();
@Override
public void add(Component component) {
childs.add(component);
}
@Override
public void remove(Component component) {
childs.remove(component);
}
@Override
public Component getChild(int index) {
return childs.get(index);
}
@Override
public void operate() {
System.out.println("composite operate");
for (Component c : childs
) {
c.operate();
}
}
}
class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void add(Component component) {
throw new UnsupportedOperationException();
}
@Override
public void remove(Component component) {
throw new UnsupportedOperationException();
}
@Override
public Component getChild(int index) {
throw new UnsupportedOperationException();
}
@Override
public void operate() {
System.out.println("leaf" + name + "operate");
}
}桥接模式
模式定义
桥接模式(Bridge):将抽象部分和实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体模式或接口模式。
模式结构
桥接模式包含 4 个角色:
- abstract:抽象类
- RefinedAbstraction:扩充抽象类的实现类
- Implementor:实现类接口
- ConcreateImplementor:具体实现类
代码分析
public class Bridge {
public static void main(String[] args) {
Abstraction abstraction = new RefinedAbstraction();
abstraction.setImplementor(new ConcreateImplementor());
abstraction.operation();
}
}
interface Implementor {
void operationImpl();
}
abstract class Abstraction {
protected Implementor implementor;
public void setImplementor(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
class RefinedAbstraction extends Abstraction {
private void doSomething() {
System.out.println("refinedAbstraction do something");
}
@Override
public void operation() {
//扩充抽象类方法,执行具体实现类方法
doSomething();
implementor.operationImpl();
}
}
class ConcreateImplementor implements Implementor {
@Override
public void operationImpl() {
System.out.println("ConcreateImplementor operationImpl");
}
}装饰模式
模式定义
装饰模式(Decorator):动态地给一个类增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更加灵活。装饰模式也叫包装器,与适配器模式同名,但使用场景不一样。装饰模式也称为油漆工模式,是一种对象结构型模式。
模式结构
装饰模式包含 4 个角色:
- Component:抽象构件
- ConcreteComponent:具体构件
- Decorator:抽象装饰类
- ConcreteDecorator:具体装饰类
代码分析
public class DecoratorPattern {
public static void main(String[] args) {
Component component = new DecoratorImpl(new ConCreateComponent());
component.use();
}
}
interface Component {
void use();
}
class ConCreateComponent implements Component {
@Override
public void use() {
System.out.println("ConCreateComponent use");
}
}
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void use() {
component.use();
}
}
class DecoratorImpl extends Decorator {
public DecoratorImpl(Component component) {
super(component);
}
public void addBehavior() {
System.out.println("DecoratorImpl addBehavior");
}
@Override
public void use() {
addBehavior();
super.use();
}
}外观模式
模式定义
外观模式(Facade):外部与子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面。外观模式定义了一个高层接口,这个接口使得子系统更易于使用。外观模式又称为门面模式,它是一种对象结构型模式。
模式结构
角色
外观模式包含 2 个角色:
- Facade:外观角色
- SubSystem:子系统角色
代码分析
public class FacadePattern {
public static void main(String[] args) {
Facade facade = new Facade();
facade.operate();
}
}
class SystemA {
void run() {
System.out.println("systemA run");
}
}
class SystemB {
void walk() {
System.out.println("systemB walk");
}
}
class SystemC {
void swim() {
System.out.println("systemC swim");
}
}
class Facade {
private SystemA systemA;
private SystemB systemB;
private SystemC systemC;
public Facade() {
systemA = new SystemA();
systemB = new SystemB();
systemC = new SystemC();
}
public void operate() {
systemA.run();
systemB.walk();
systemC.swim();
}
}享元模式
模式定义
享元模式(Flyweight):运用共享技术有效地支持大量细颗粒度对象的复用,系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细颗粒度的对象,因此它又称为轻量级模式,它是一种对象结构型模式。
模式结构
角色
享元模式包含 4 个角色:
- Flyweight:抽象享元类
- ConcreteFlyweight:共享具体享元类
- UnsharedConcreteFlyweight:非共享具体享元类
- FlyweightFactory:享元工厂类
代码分析
public class FlyweightPattern {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight = factory.get("one");
flyweight.use("1");
flyweight = factory.get("two");
flyweight.use("2");
flyweight = factory.get("one");
flyweight.use("3");
}
}
interface Flyweight {
void use(String str);
}
class ConcreateFlyweight implements Flyweight {
private String name;
public ConcreateFlyweight(String name) {
this.name = name;
}
@Override
public void use(String str) {
System.out.println("ConcreateFlyweight " + name + " use " + str);
}
}
class FlyweightFactory {
Map<String, Flyweight> map = new HashMap<String, Flyweight>();
public Flyweight get(String name) {
if (map.containsKey(name)) {
return map.get(name);
} else {
Flyweight flyweight = new ConcreateFlyweight(name);
map.put(name, flyweight);
return flyweight;
}
}
}代理模式
模式定义
代理模式(Proxy):给某一个对象提供一个代理,并由代理对象控制对原对象的引用。代理模式英文叫做 Proxy 或 Surrogate,它是一种对象结构型模式。
模式结构
角色
代理模式包含 3 个角色:
- Subject: 抽象主题角色
- Proxy: 代理主题角色
- RealSubject: 真实主题角色
代码分析
public class ProxyPattern {
public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.request();
}
}
abstract class Subject {
public abstract void request();
}
class RealSubject extends Subject {
@Override
public void request() {
System.out.println("realsubject run");
}
}
class Proxy extends Subject {
private RealSubject realSubject;
public Proxy() {
realSubject = new RealSubject();
}
private void preRequest() {
System.out.println("proxy preRequest");
}
private void afterRequest() {
System.out.println("proxy afterRequest");
}
@Override
public void request() {
preRequest();
realSubject.request();
afterRequest();
}
}责任链模式
模式定义
责任链模式(Chain of Responsibility):为了避免请求发送者与多个请求处理者耦合在一起,将所有请求处理者通过前一对象记住下一个对象的引用的方式连成一条链,这条链就叫责任链。当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。责任链模式是一个对象行为型模式。
模式结构
角色
责任链模式包含 3 个角色:
- Handler:抽象处理者
- ConCreateHandler:具体处理者
- Client:客户类
代码分析
public class ChainOfResponsibilityPattern {
public static void main(String[] args) {
Handler handlerA = new ConCreateHandlerA();
Handler handlerB = new ConCreateHandlerB();
Handler handlerC = new ConCreateHandlerC();
handlerA.setNextHandler(handlerB);
handlerB.setNextHandler(handlerC);
handlerA.handle(3);
}
}
abstract class Handler {
private Handler nextHandler;
public Handler getNextHandler() {
return nextHandler;
}
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public abstract void handle(int level);
}
class ConCreateHandlerA extends Handler {
@Override
public void handle(int level) {
if (level == 1) {
System.out.println("handler A handle");
} else {
Optional.ofNullable(getNextHandler()).ifPresentOrElse(h -> h.handle(level), () -> System.out.println("无法处理"));
}
}
}
class ConCreateHandlerB extends Handler {
@Override
public void handle(int level) {
if (level == 2) {
System.out.println("handler B handle");
} else {
Optional.ofNullable(getNextHandler()).ifPresentOrElse(h -> h.handle(level), () -> System.out.println("无法处理"));
}
}
}
class ConCreateHandlerC extends Handler {
@Override
public void handle(int level) {
if (level == 3) {
System.out.println("handler C handle");
} else {
Optional.ofNullable(getNextHandler()).ifPresentOrElse(h -> h.handle(level), () -> System.out.println("无法处理"));
}
}
}命令行模式
模式定义
命令模式(Command):将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;在该模式下,可以进行请求排队或记录请求日志,以及支持重做、撤销等操作。命令模式是一个对象行为型模式,可被称为行动(Action)模式或事务(Transaction)模式。
模式结构
角色
命令模式包含 5 个角色:
- Command:抽象命令类
- ConcreteCommand:具体命令类
- Invoker:调用者
- Receiver:接收者
- Client:客户类
代码分析
public class CommandPattern {
public static void main(String[] args) {
Invoker invoker = new Invoker();
Receiver receiver = new Receiver();
Command command = new ConCreateCommand(receiver);
invoker.call(command);
}
}
interface Command {
void execute();
}
class Receiver {
public void action() {
System.out.println("receiver action A");
}
}
class ConCreateCommand implements Command {
private Receiver receiver;
public ConCreateCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action();
}
}
class Invoker {
void call(Command command) {
command.execute();
}
}解释器模式
模式定义
解释器模式(Interpreter):给分析对象定义一个语言,并定义该语言的文法表示,再设计一个解释器解释语言中的句子。也就是说,用编译语言的方式来分析应用中的实例。这种模式实现了文法表达式处理的接口,该接口解释一个特定的上下文。解释器模式是一种类行为型模式。
模式结构
角色
解释器模式包含 5 个角色:
- Abstract Expression:抽象表达式
- Terminal Expression:终结表达式
- NonTerminal Expression:非终结表达式
- Context:环境角色
- Client:客户端
代码分析
public class InterpreterPattern {
public static void main(String[] args) {
Context context = new Context();
int result = context.operation("1+99");
System.out.println(result);
}
}
interface Expression {
int interpreter(String str);
}
class TerminalExpression implements Expression {
@Override
public int interpreter(String str) {
return Integer.valueOf(str).intValue();
}
}
class AddExpression implements Expression {
private Expression left;
private Expression rigth;
public AddExpression(Expression left, Expression rigth) {
this.left = left;
this.rigth = rigth;
}
@Override
public int interpreter(String str) {
String[] strs = str.split("\\+", 2);
return left.interpreter(strs[0]) + rigth.interpreter(strs[1]);
}
}
class Context {
private Expression expression;
public Context() {
Expression number = new TerminalExpression();
Expression add = new AddExpression(number, number);
this.expression = add;
}
public int operation(String str) {
return expression.interpreter(str);
}
}迭代器模式
模式定义
迭代器模式(Iterator):提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示。迭代器模式是一种对象行为型模式。
模式结构
角色
迭代器模式包含 4 个角色:
- Aggregate:抽象聚合角色
- ConcreateAggregate:具体聚合角色
- Iterator:抽象迭代器角色
- ConcreateIterator:具体迭代器角色
代码分析
public class IteratorPattern {
public static void main(String[] args) {
Aggregate aggregate = new ConcreateAggregate();
Iterator iterator = aggregate.getIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
interface Iterator {
boolean hasNext();
Object next();
}
interface Aggregate {
Iterator getIterator();
}
class ConcreateAggregate implements Aggregate {
List<Object> objectList = new ArrayList<>();
public ConcreateAggregate() {
objectList.add(new Object());
objectList.add(new Object());
objectList.add(new Object());
objectList.add(new Object());
objectList.add(new Object());
}
@Override
public Iterator getIterator() {
return new ConcreateIterator(objectList);
}
}
class ConcreateIterator implements Iterator {
private List list;
private int index = 0;
public ConcreateIterator(List list) {
this.list = list;
}
@Override
public boolean hasNext() {
if (index <= list.size() - 1)
return true;
else
return false;
}
@Override
public Object next() {
if (hasNext())
return list.get(index++);
else
return null;
}
}中介者模式
模式定义
中介者模式(Mediator):用一个中介对象封装一系列对象间的交互,中介者对象使各对象不需要显示地互相引用,从而使其耦合松散,而且中介者对象可以独立地改变对象之间的交互。中介者模式又称为调停者模式,它是一种行为对象型模式。
模式结构
角色
中介者模式包含 4 个角色:
- Mediator:抽象中介者
- ConcreteMediator:具体中介者
- Colleague:抽象同事类
- ConcreteColleague:具体同事类
代码分析
public class MediatorPattern {
public static void main(String[] args) {
Colleague a = new CollageA();
Colleague b = new CollageB();
Mediator m = new ConCreateMediator();
m.register("A", a);
m.register("B", b);
a.sendMsg("B");
b.sendMsg("A");
}
}
abstract class Colleague {
protected Mediator mediator;
public abstract void sendMsg(String to);
public abstract void receiveMsg();
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
}
abstract class Mediator {
final protected Map<String, Colleague> colleagueHashMap = new HashMap<String, Colleague>();
public abstract void operator(String col);
public void register(String str, Colleague colleague) {
colleagueHashMap.put(str, colleague);
colleague.setMediator(this);
}
}
class CollageA extends Colleague {
@Override
public void sendMsg(String to) {
System.out.println("collageA send to " + to);
mediator.operator(to);
}
@Override
public void receiveMsg() {
System.out.println("collageA receiveMsg");
}
}
class CollageB extends Colleague {
@Override
public void sendMsg(String to) {
System.out.println("collageB send to " + to);
mediator.operator(to);
}
@Override
public void receiveMsg() {
System.out.println("collageB receiveMsg");
}
}
class ConCreateMediator extends Mediator {
@Override
public void operator(String col) {
Colleague colleague = colleagueHashMap.get(col);
Optional.ofNullable(colleague).ifPresent(c -> c.receiveMsg());
}
}备忘录模式
模式定义
备忘录模式(Memento):是指在不破坏封装类的前提下,捕获对象的内部状态,并将状态保存在对象之外,在我们需要的时候将该对象恢复到原先保存的状态,备忘录模式属于对象行为型模式。它也被称为快照模式(Snapshop Pattern)或者令牌模式(Token Pattern)。
模式结构
角色
备忘录模式包含 3 个角色:
- Originator:发起人
- Memento:备忘录
- Caretaker:备忘录管理者
代码分析
public class MementoPattern {
public static void main(String[] args) {
Originator originator = new Originator();
CareTaker careTaker = new CareTaker();
originator.setState("1");
System.out.println(originator.getState());
careTaker.addMemento(originator.saveStateToMemento());
originator.setState("2");
System.out.println(originator.getState());
originator.getStateFromMemento(careTaker.getMemento(0));
System.out.println(originator.getState());
}
}
class Originator {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Memento saveStateToMemento() {
return new Memento(this.state);
}
public void getStateFromMemento(Memento memento) {
this.state = memento.getState();
}
}
class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
class CareTaker {
List<Memento> mementoList = new ArrayList<Memento>();
public void addMemento(Memento memento) {
mementoList.add(memento);
}
public void removeMemento(int index) {
mementoList.remove(index);
}
public Memento getMemento(int index) {
return mementoList.get(index);
}
}观察者模式
模式定义
观察者模式(Observer):定义对象间的一种一对多的依赖关系,使得当一个对象状态发生改变时,依赖其的相关对象皆得到通知及被自动更新。观察者模式是一种对象行为型模式,也被称为订阅-发布模式,模式-视图模式,源-监听模式。
模式结构
角色
观察者模式包含 4 个角色:
- Subject:目标
- ConCreateSubject:具体目标
- Observer:观察者
- ConCreateObserver:具体观察者
代码分析
public class ObserverPattern {
public static void main(String[] args) {
Subject subject = new ConCreateSubject();
Observer a = new ConCreateObserver("A");
Observer b = new ConCreateObserver("B");
Observer c = new ConCreateObserver("C");
subject.attach(a);
subject.attach(b);
subject.attach(c);
subject.notifyObserver();
subject.detach(c);
subject.notifyObserver();
}
}
interface Observer {
void update();
}
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObserver();
}
class ConCreateSubject implements Subject {
List<Observer> observerList = new ArrayList<Observer>();
@Override
public void attach(Observer observer) {
if (observerList.contains(observer) == false) {
observerList.add(observer);
}
}
@Override
public void detach(Observer observer) {
observerList.remove(observer);
}
@Override
public void notifyObserver() {
for (Observer o : observerList
) {
o.update();
}
}
}
class ConCreateObserver implements Observer {
private String name;
public ConCreateObserver(String name) {
this.name = name;
}
@Override
public void update() {
System.out.println("subject " + name + " update");
}
}状态模式
模式定义
状态模式(State):允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。其别名为状态对象,状态模式是一种对象行为型模式。
模式结构
角色
状态模式包含 3 个角色:
- Context:环境类
- State:抽象状态类
- ConCreateState:具体状态类
代码分析
public class StatePattern {
public static void main(String[] args) {
Context context = new Context();
context.setState(new StateA());
context.request();
context.request();
}
}
interface State {
void handler(Context context);
}
class Context {
private State state;
public void request() {
state.handler(this);
}
public void setState(State state) {
this.state = state;
}
}
class StateA implements State {
@Override
public void handler(Context context) {
System.out.println("stateA handler");
context.setState(new StateB());
}
}
class StateB implements State {
@Override
public void handler(Context context) {
System.out.println("stateB handler");
}
}策略模式
模式定义
策略模式(Strategy):定义一系列算法,并将每一个算法封装起来,并让它们可以互相替换。策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。
模式结构
角色
策略模式包含 3 个角色:
- Context:环境类
- Strategy:抽象策略类
- ConCreateStrategy:具体策略类
代码分析
public class StrategyPattern {
public static void main(String[] args) {
Context context = new Context();
context.algorithm(new StrategyA());
context.algorithm(new StrategyB());
}
}
interface Strategy {
void algorithm();
}
class Context {
public void algorithm(Strategy strategy) {
strategy.algorithm();
}
}
class StrategyA implements Strategy {
@Override
public void algorithm() {
System.out.println("strategy A algorithm");
}
}
class StrategyB implements Strategy {
@Override
public void algorithm() {
System.out.println("strategy B algorithm");
}
}模板方法
模式定义
模板方法(Template Method):定义了一个操作的算法骨架,并将算法中的一些步骤延迟到子类中去实现,模板方法使得子类在不改变算法结构的情况下,重新定义算法的某些特定步骤的具体实现。它是一种行为型模式。
模式结构
角色
- Abstract Method:抽象方法
- Concreate Method:具体方法
- Hook Method:钩子方法
代码分析
public class TemplateMethodPattern {
public static void main(String[] args) {
AbstractClass a = new SpecificClassA();
AbstractClass b = new SpecificClassB();
a.templateMethod();
b.templateMethod();
}
}
abstract class AbstractClass {
public final void templateMethod() {
specificMethodA();
specificMethodB();
abstractMethod();
}
private void specificMethodA() {
System.out.println("specifi method A");
}
public boolean hookMethod() {
return true;
}
private void specificMethodB() {
if (hookMethod())
System.out.println("specifi method B");
}
public abstract void abstractMethod();
}
class SpecificClassA extends AbstractClass {
@Override
public void abstractMethod() {
System.out.println("specificClassA abstractMethod");
}
}
class SpecificClassB extends AbstractClass {
@Override
public boolean hookMethod() {
return false;
}
@Override
public void abstractMethod() {
System.out.println("specificClassB abstractMethod");
}
}访问者模式
模式定义
访问者模式(Visitor):在一个包含各种类型元素类的对象结构中,我们可以使用一个访问者类,它可以在不改变各元素类的前提下定义作用于这些元素的新操作。它是一种对象行为型模式。
模式结构
角色
访问者模式包含 4 个角色:
- ObjectStructure:对象结构
- Element:元素
- ConcreateElement:具体元素
- Visitor:访问者
- ConcreateVisitor:具体访问者
代码分析
public class VisitorPattern {
public static void main(String[] args) {
ObjectStruct objectStruct = new ObjectStruct();
Visitor visitorX = new VisitorX();
Visitor visitorY = new VisitorY();
objectStruct.accept(visitorX);
objectStruct.accept(visitorY);
}
}
interface Element {
void accept(Visitor visitor);
}
interface Visitor {
void visit(ElementA elementA);
void visit(ElementB elementB);
}
class ElementA implements Element {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class ElementB implements Element {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class VisitorX implements Visitor {
@Override
public void visit(ElementA elementA) {
System.out.println("visitor X visit " + elementA);
}
@Override
public void visit(ElementB elementB) {
System.out.println("visitor X visit " + elementB);
}
}
class VisitorY implements Visitor {
@Override
public void visit(ElementA elementA) {
System.out.println("visitor Y visit " + elementA);
}
@Override
public void visit(ElementB elementB) {
System.out.println("visitor Y visit " + elementB);
}
}
class ObjectStruct {
private List<Element> elements = new ArrayList<Element>();
public ObjectStruct() {
elements.add(new ElementA());
elements.add(new ElementB());
}
public void accept(Visitor visitor) {
for (Element e : elements
) {
e.accept(visitor);
}
}
}