GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Update 装饰设计模式.MD · WhCannon/JavaSE@d503463

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Design-pattern
    • 装饰设计模式.MD
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Design-pattern/装饰设计模式.MD‎

Copy file name to clipboard
+33Lines changed: 33 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -1 +1,34 @@
11
# 装饰设计模式
2+
对一组对象的功能进行增强时,就可以使用该模式进行问题的解决。
3+
装饰和继承都能实现一样的特点:进行功能的扩展增强。有什么区别?
4+
假设有一个继承体系:
5+
Writer
6+
|--TextWriter: 用于操作文本
7+
|--MediaWriter: 用于操作媒体
8+
想要对操作的动作进行效率的提高。按照面向对象,可以通过继承对具体的操作进行功能的扩展,而效率提高需要加入缓冲技术。
9+
Writer
10+
|--TextWriter:用于操作文本
11+
|--BufferTextWriter:加入了缓冲技术的操作文本的对象(操作+缓冲)
12+
|--MediaWriter:用于操作媒体。
13+
|--BufferMediaWriter:操作+缓冲
14+
到这里就哦了,但是这样做好像并不理想。如果这个体系进行功能扩展,又多了一些流对象,那么这个流要提高效率,是不是也要产生子类呢?是。
15+
这时就会发现只为提高功能而进行的继承,会导致继承体系越来越臃肿,不够灵活。
16+
重新思考这个问题?
17+
既然不同的流加入的都是同一种技术--缓冲,上面的方法是让缓冲和每一个具体的对象相结合。那就可以将缓冲进行单独的封装,哪个对象需要缓冲就将哪个对象和缓冲关联(通过构造函数传入需要被关联的对象)
18+
class Buffer{
19+
Buffer(TextWriter w)
20+
{}
21+
Buffer(MediaWirter w)
22+
{}
23+
}
24+
可以对代码改进,采用多态的方法:
25+
class BufferWriter extends Writer{//多态,可以操作父类及其子类
26+
BufferWriter(Writer w)
27+
{}
28+
}
29+
Writer
30+
|--TextWriter:用于操作文本
31+
|--MediaWriter:用于操作媒体。
32+
|--BufferWriter:用于提高Writer效率。
33+
装饰比继承灵活。IO流的缓冲区就是用这种思想创建出来的。这种思想可以用到其他的Java体系上。
34+
注意:装饰类和被装饰类都必须所属同一个接口或者父类。

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.