1 创建型模式
这些设计模式提供了一种在创建对象的同时隐藏创建逻辑的方式,而不是使用 new 运算符直接实例化对象。这使得程序在判断针对某个给定实例需要创建哪些对象时更加灵活。
工厂模式(Factory Pattern)
1
2
3
4
5
6
7ShapeFactory shapeFactory = new ShapeFactory();
// 获取 Circle 的对象,并调用它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
// 调用 Circle 的 draw 方法
shape1.draw();
反射机制可以解决每次增加一个产品时,都需要增加一个对象实现工厂的缺点
抽象工厂模式(Abstract Factory Pattern)
1
2
3
4
5
6
7
8// 获取形状工厂
AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
// 获取形状为 Circle 的对象
Shape shape1 = shapeFactory.getShape("CIRCLE");
// 调用 Circle 的 draw 方法
shape1.draw();
单例模式(Singleton Pattern)
1
2// 获取唯一可用的对象
SingleObject object = SingleObject.getInstance();
单例实现方式
1 | public class MealBuilder { |
原型模式(Prototype Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33import java.util.Hashtable;
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap
= new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
// 对每种形状都运行数据库查询,并创建该形状
// shapeMap.put(shapeKey, shape);
// 例如,我们要添加三种形状
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(),rectangle);
}
}
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape :" + clonedShape.getType());
2 结构型模式
这些设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。
适配器模式(Adapter Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc") ){
advancedMusicPlayer = new VlcPlayer();
} else if (audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new Mp4Player();
}
}
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
桥接模式(Bridge Pattern)
1
2
3
4
5
6
7public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
过滤器模式(Filter、Criteria Pattern)
1
2
3
4
5
6List<Person> malePersons = new ArrayList<Person>();
for (Person person : persons) {
if(person.getGender().equalsIgnoreCase("MALE")){
malePersons.add(person);
}
}
组合模式(Composite Pattern)
1
2
3Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
CEO.add(headSales);
装饰器模式(Decorator Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}
1 | Shape redCircle = new RedShapeDecorator(new Circle()); |
外观模式(Facade Pattern)
1
2
3
4
5
6
7
8
9
10
11public class ShapeMaker {
private Shape circle;
public ShapeMaker() {
circle = new Circle();
}
public void drawCircle(){
circle.draw();
}
}
1 | ShapeMaker shapeMaker = new ShapeMaker(); |
享元模式(Flyweight Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class ShapeFactory {
private static final HashMap<String, Shape> circleMap = new HashMap<>();
public static Shape getCircle(String color) {
Circle circle = (Circle)circleMap.get(color);
if(circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color :" + color);
}
return circle;
}
}
1 | Circle circle = (Circle)ShapeFactory.getCircle("RED""); |
代理模式(Proxy Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class ProxyImage implements Image{
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName){
this.fileName = fileName;
}
public void display() {
if(realImage == null){
realImage = new RealImage(fileName);
}
realImage.display();
}
}
3 行为型模式
这些设计模式特别关注对象之间的通信。
责任链模式(Chain of Responsibility Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public abstract class AbstractLogger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected int level;
// 责任链中的下一个元素
protected AbstractLogger nextLogger;
public void setNextLogger(AbstractLogger nextLogger){
this.nextLogger = nextLogger;
}
public void logMessage(int level, String message){
if(this.level <= level){
write(message);
}
if(nextLogger !=null){
nextLogger.logMessage(level, message);
}
}
abstract protected void write(String message);
}
命令模式(Command Pattern)
1
2
3
4
5
6
7
8
9
10
11public class BuyStock implements Order {
private Stock abcStock;
public BuyStock(Stock abcStock){
this.abcStock = abcStock;
}
public void execute() {
abcStock.buy();
}
}
解释器模式(Interpreter Pattern)
1
2
3
4
5
6
7
8public static Expression getMaleExpression(){
Expression robert = new TerminalExpression("Robert");
Expression john = new TerminalExpression("John");
return new OrExpression(robert, john);
}
Expression isMale = getMaleExpression();
System.out.println("John is male?" + isMale.interpret("John"));
迭代器模式(Iterator Pattern)
中介者模式(Mediator Pattern)
备忘录模式(Memento Pattern)
观察者模式(Observer Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class Subject {
private List<Observer> observers
= new ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
// 状态发生变化时,自动通知观察者
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
状态模式(State Pattern)
空对象模式(Null Object Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13public class CustomerFactory {
public static final String[] names = {"Rob", "Joe", "Julie"};
public static AbstractCustomer getCustomer(String name){
for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(name)){
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}
策略模式(Strategy Pattern)
模板模式(Template Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
// 模板
public final void play(){
// 初始化游戏
initialize();
// 开始游戏
startPlay();
// 结束游戏
endPlay();
}
}
访问者模式(Visitor Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Computer implements ComputerPart {
ComputerPart[] parts;
public Computer(){
parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
}
public void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < parts.length; i++) {
parts[i].accept(computerPartVisitor);
}
computerPartVisitor.visit(this);
}
}
1 | ComputerPart computer = new Computer(); |
4 J2EE 模式
这些设计模式特别关注表示层。这些模式是由 Sun Java Center 鉴定的。
MVC 模式(MVC Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14// 从数据可获取学生记录
Student model = retriveStudentFromDatabase();
// 创建一个视图:把学生详细信息输出到控制台
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
// 更新模型数据
controller.setStudentName("John");
controller.updateView();
业务代表模式(Business Delegate Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class BusinessDelegate {
private BusinessLookUp lookupService = new BusinessLookUp();
private BusinessService businessService;
private String serviceType;
public void setServiceType(String serviceType){
this.serviceType = serviceType;
}
public void doTask(){
businessService = lookupService.getBusinessService(serviceType);
businessService.doProcessing();
}
}
组合实体模式(Composite Entity Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public class CoarseGrainedObject {
DependentObject1 do1 = new DependentObject1();
DependentObject2 do2 = new DependentObject2();
public void setData(String data1, String data2){
do1.setData(data1);
do2.setData(data2);
}
public String[] getData(){
return new String[] {do1.getData(),do2.getData()};
}
}
public class CompositeEntity {
private CoarseGrainedObject cgo = new CoarseGrainedObject();
public void setData(String data1, String data2){
cgo.setData(data1, data2);
}
public String[] getData(){
return cgo.getData();
}
}
数据访问对象模式(Data Access Object Pattern)
1
2
3
4
5
6public interface StudentDao {
public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}
前端控制器模式(Front Controller Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class FrontController {
private Dispatcher dispatcher;
public FrontController(){
dispatcher = new Dispatcher();
}
private boolean isAuthenticUser(){
System.out.println("User is authenticated successfully.");
return true;
}
private void trackRequest(String request){
System.out.println("Page requested:" + request);
}
public void dispatchRequest(String request){
// 记录每一个请求
trackRequest(request);
// 对用户进行身份验证
if(isAuthenticUser()){
dispatcher.dispatch(request);
}
}
}
拦截过滤器模式(Intercepting Filter Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public class FilterChain {
private List<Filter> filters = new ArrayList<Filter>();
private Target target;
public void addFilter(Filter filter){
filters.add(filter);
}
public void execute(String request){
for (Filter filter : filters) {
filter.execute(request);
}
target.execute(request);
}
public void setTarget(Target target){
this.target = target;
}
}
服务定位器模式(Service Locator Pattern)
1 | public class ServiceLocator { |
传输对象模式(Transfer Object Pattern)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18// 类似于 Service 层
StudentBO studentBusinessObject = new StudentBO();
// 输出所有的学生
for (StudentVO student : studentBusinessObject.getAllStudents()) {
System.out.println("Student: [RollNo :"
+student.getRollNo()+", Name :"+student.getName()+"]");
}
// 更新学生
StudentVO student =studentBusinessObject.getAllStudents().get(0);
student.setName("Michael");
studentBusinessObject.updateStudent(student);
// 获取学生
studentBusinessObject.getStudent(0);
System.out.println("Student: [RollNo :"
+student.getRollNo()+", Name :"+student.getName()+"]");