1 创建型模式
这些设计模式提供了一种在创建对象的同时隐藏创建逻辑的方式,而不是使用 new 运算符直接实例化对象。这使得程序在判断针对某个给定实例需要创建哪些对象时更加灵活。
工厂模式(Factory Pattern)
1 | ShapeFactory shapeFactory = new ShapeFactory(); |
反射机制可以解决每次增加一个产品时,都需要增加一个对象实现工厂的缺点
抽象工厂模式(Abstract Factory Pattern)
1 | // 获取形状工厂 |
单例模式(Singleton Pattern)
1 | // 获取唯一可用的对象 |
单例实现方式
1 | public class MealBuilder { |
原型模式(Prototype Pattern)
1 | import java.util.Hashtable; |
2 结构型模式
这些设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。
适配器模式(Adapter Pattern)
1 | public class MediaAdapter implements MediaPlayer { |
桥接模式(Bridge Pattern)
1 | public abstract class Shape { |
过滤器模式(Filter、Criteria Pattern)
1 | List<Person> malePersons = new ArrayList<Person>(); |
组合模式(Composite Pattern)
1 | Employee CEO = new Employee("John","CEO", 30000); |
装饰器模式(Decorator Pattern)
1 | public class RedShapeDecorator extends ShapeDecorator { |
1 | Shape redCircle = new RedShapeDecorator(new Circle()); |
外观模式(Facade Pattern)
1 | public class ShapeMaker { |
1 | ShapeMaker shapeMaker = new ShapeMaker(); |
享元模式(Flyweight Pattern)
1 | public class ShapeFactory { |
1 | Circle circle = (Circle)ShapeFactory.getCircle("RED""); |
代理模式(Proxy Pattern)
1 | public class ProxyImage implements Image{ |
3 行为型模式
这些设计模式特别关注对象之间的通信。
责任链模式(Chain of Responsibility Pattern)
1 | public abstract class AbstractLogger { |
命令模式(Command Pattern)
1 | public class BuyStock implements Order { |
解释器模式(Interpreter Pattern)
1 | public static Expression getMaleExpression(){ |
迭代器模式(Iterator Pattern)
中介者模式(Mediator Pattern)
备忘录模式(Memento Pattern)
观察者模式(Observer Pattern)
1 | public class Subject { |
状态模式(State Pattern)
空对象模式(Null Object Pattern)
1 | public class CustomerFactory { |
策略模式(Strategy Pattern)
模板模式(Template Pattern)
1 | public abstract class Game { |
访问者模式(Visitor Pattern)
1 | public class Computer implements ComputerPart { |
1 | ComputerPart computer = new Computer(); |
4 J2EE 模式
这些设计模式特别关注表示层。这些模式是由 Sun Java Center 鉴定的。
MVC 模式(MVC Pattern)
1 | // 从数据可获取学生记录 |
业务代表模式(Business Delegate Pattern)
1 | public class BusinessDelegate { |
组合实体模式(Composite Entity Pattern)
1 | public class CoarseGrainedObject { |
数据访问对象模式(Data Access Object Pattern)
1 | public interface StudentDao { |
前端控制器模式(Front Controller Pattern)
1 | public class FrontController { |
拦截过滤器模式(Intercepting Filter Pattern)
1 | public class FilterChain { |
服务定位器模式(Service Locator Pattern)
1 | public class ServiceLocator { |
传输对象模式(Transfer Object Pattern)
1 | // 类似于 Service 层 |