本文共 11208 字,大约阅读时间需要 37 分钟。
在软件开发中,设计模式就像是一把精准的工具包,可以帮助我们应对常见的设计挑战。通过学习和理解这些模式,我们能够写出更规范、更高效的代码,同时在面试中也能成为一道亮眼的选手。
设计模式主要分为三大类:
这些模式关注对象的创建过程,主要包括:
这些模式关注对象的结构,主要包括:
这些模式关注对象的行为,主要包括:
确保某一个类只有一个实例,并通过自行实例化向系统提供该实例。
public class Singleton { private static final Singleton singleton = new Singleton(); private Singleton() {} public static Singleton getSingleton() { return singleton; } public static void doSomething() {}} 定义一个用于创建对象的接口,让子类决定实例化哪一个类。
public abstract class Creator { public abstract T createProduct(Class clazz);} 为创建一组相关或相互依赖的对象提供一个接口,不需要指定具体类。
public abstract class AbstractCreator { public abstract AbstractProductA createProductA(); public abstract AbstractProductB createProductB();} 定义一个操作的框架,子类可以重定义部分逻辑。
public abstract class AbstractClass { public abstract void TemplateMethod(); public void SpecificMethod() { System.out.println("抽象类中的具体方法被调用..."); }} 将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
public class ConcreteProduct extends Builder { private Product product = new Product(); public void setPart() {} public Product buildProduct() { return product; }} 为其他对象提供一种代理,以控制对该对象的访问。
public class Client { private A a = new A(); public void methodA() { a.doSomething(); }} 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新对象。
public class PrototypeClass implements Cloneable { @Override public PrototypeClass clone() { try { return (PrototypeClass) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } }} 用一个中介对象封装一系列对象交互,使对象耦合松散。
public abstract class Mediator { protected ConcreteColleague1 c1; protected ConcreteColleague2 c2; public abstract void doSomething1(); public abstract void doSomething2();} 将请求封装成一个对象,便于管理和撤销。
public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void action() { this.command.execute(); }} 使多个对象都有机会处理请求,避免耦合。
public abstract class Handler { private Handler nextHandler; public Response handleMessage(Request request) { if (this.getHandlerLevel().equals(request.getRequestLevel())) { return this.echo(request); } else { if (this.nextHandler != null) { return this.nextHandler.handleMessage(request); } else { // 没有适当的处理者 } } return response; } public void setNext(Handler _handler) { this.nextHandler = _handler; } protected abstract Level getHandlerLevel(); protected abstract Response echo(Request request);} 动态地给一个对象添加额外职责。
public class BufferedReader implements Reader { private Reader reader; public void readLine() { read(); System.out.println("并且仅仅读取一行"); }} 定义一组算法,允许动态切换算法。
public enum Calculator { ADD("+") { public int exec(int a, int b) { return a + b; } }, SUB("-") { public int exec(int a, int b) { return a - b; } }; String value; private Calculator(String _value) { this.value = _value; } public String getValue() { return this.value; } public abstract int exec(int a, int b);} 将一个类的接口转换为另一个类的接口。
public class Adapter extends Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); }} 提供一种方法访问容器对象中的各个元素。
public class ConcreteIterator implements Iterator { private List list = new ArrayList(); private int cursor = 0; public boolean hasNext() { return cursor != list.size(); } public Object next() { Object obj = null; if (this.hasNext()) { obj = this.list.get(cursor++); } return obj; }} 将对象组合成树形结构,表示“部分-整体”关系。
public class Composite extends Component { private List componentArrayList = new ArrayList(); public void add(Component component) { this.componentArrayList.add(component); } public void remove(Component component) { this.componentArrayList.remove(component); } public List getChildren() { return this.componentArrayList; }} 定义对象间的一对多依赖关系,自动通知依赖对象。
public abstract class Subject { private Vector obsVector = new Vector(); public void addObserver(Observer o) { this.obsVector.add(o); } public void delObserver(Observer o) { this.obsVector.remove(o); } public void notifyObservers() { for (Observer o : this.obsVector) { o.update(); } }} 为一个子系统提供一个统一的接口,屏蔽内部细节。
public class Client { private A a = new A(); private B b = new B(); private C c = new C(); public void methodA() { a.doSomething(); } public void methodB() { b.doSomething(); } public void methodC() { c.doSomething(); }} 在不破坏封装性的前提下,捕获对象的内部状态。
public class BeanUtils { public static HashMap backupProp(Object bean) { HashMap result = new HashMap(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor des : descriptors) { String fieldName = des.getName(); if (!fieldName.equalsIgnoreCase("class")) { Method getter = des.getReadMethod(); Object fieldValue = getter.invoke(bean, new Object[] {}); result.put(fieldName, fieldValue); } } } catch (Exception e) { // 异常处理 } return result; } public static void restoreProp(Object bean, HashMap propMap) { try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor des : descriptors) { String fieldName = des.getName(); if (propMap.containsKey(fieldName)) { Method setter = des.getWriteMethod(); setter.invoke(bean, new Object[]{propMap.get(fieldName)}); } } } catch (Exception e) { // 异常处理 } }} 封装作用于数据结构中的各元素的操作。
public class CompensationVisitor implements Visitor { @Override public void Visit(Employee element) { System.out.println("'s Compensation is " + (element.getDegree() * element.getVacationDays() * 10)); }} 当一个对象的内在状态改变时,允许其行为改变,类似于改变了其类。
public abstract class State { protected Context context; public void setContext(Context _context) { this.context = _context; } public abstract void handle1(); public abstract void handle2();} 给定一门语言,定义其文法,并定义一个解释器来解释语言句子。
public class TerminalExpression extends AbstractExpression { @Override public void interpret(Context ctx) { // 实现与语法规则中的终结符相关联的解释操作 }}public class NonterminalExpression extends AbstractExpression { @Override public void interpret(Context ctx) { // 实现与语法规则中的非终结符相关联的解释操作 }} 通过共享对象来有效支持大量的细粒度对象。
public class FlyweightFactory { private static HashMap pool = new HashMap<>(); public static Flyweight getFlyweight(String extrinsic) { Flyweight flyweight = pool.get(extrinsic); if (flyweight == null) { flyweight = new ConcreteFlyweight1(extrinsic); pool.put(extrinsic, flyweight); } return flyweight; }} 将抽象和实现解耦,使其能够独立变化。
public abstract class Abstraction { private Implementor imp; public Abstraction(Implementor _imp) { this.imp = _imp; } public void request() { this.imp.doSomething(); } public Implementor getImp() { return imp; }} 设计模式是前人总结的经验宝库,它们为我们提供了一套解决常见问题的标准方案。通过不断学习和实践这些模式,我们能够写出更规范、更高效的代码,同时在面试中也能展现出专业的知识。
转载地址:http://vwbfz.baihongyu.com/