资讯专栏INFORMATION COLUMN

装饰模式-使用装饰器来写表单验证插件

scola666 / 3534人阅读

摘要:装饰模式描述装饰模式装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。具体装饰角色负责给构件对象添加上附加的责任。

装饰模式 描述

</>复制代码

  1. 装饰模式:装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
适用性-百科

以下情况使用Decorator模式:

需要扩展一个类的功能,或给一个类添加附加职责。

需要动态的给一个对象添加功能,这些功能可以再动态的撤销。

需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。

当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

代码示例

在装饰模式中的各个角色有:

抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。

装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。

具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。

</>复制代码

  1. // Component类 定义一个对象接口,可以给这些对象动态的添加职责
  2. abstract class Component {
  3. abstract Operation (): void
  4. }
  5. // ConcreteComponent 类定义一个具体的对象,也可以给这个对象添加职责
  6. class ConcreteComponent extends Component {
  7. Operation () {
  8. console.log("具体的对象操作");
  9. }
  10. }
  11. // Decorator 装饰抽象类,继承了Component 从外类来拓展Component的功能,但是对于Component来说,无需知道Decorator的存在
  12. abstract class Decorator extends Component{
  13. protected component: Component | null = null
  14. // 装载Component
  15. SetComponent (component: Component) {
  16. this.component = component
  17. }
  18. // 重写Operation,实际执行的是component的Operation
  19. Operation () {
  20. if (this.component !== null) {
  21. this.component.Operation()
  22. }
  23. }
  24. }
  25. // ConcreteDecorator 具体的装饰对象 起到给Component类添加职责
  26. class ConcreteDecoratorA extends Decorator {
  27. private addState: string = ""
  28. Operation () {
  29. // 先运行装饰对象的Operation,如果有的话
  30. super.Operation()
  31. this.addState = "new stateA"
  32. console.log("具体装饰对象A的操作");
  33. }
  34. }
  35. class ConcreteDecoratorB extends Decorator {
  36. Operation () {
  37. super.Operation()
  38. this.AddedBehavior()
  39. console.log("具体装饰对象b的操作");
  40. }
  41. AddedBehavior () {
  42. console.log("new state B");
  43. }
  44. }
  45. // 调用
  46. const c = new ConcreteComponent()
  47. const d1 = new ConcreteDecoratorA()
  48. const d2 = new ConcreteDecoratorB()
  49. d1.SetComponent(c) // d1装饰的是c
  50. d2.SetComponent(d1) // d2装饰的是d1
  51. d2.Operation() // d2.Operation中先会调用d1的Operation,d1.Operation中先会调用c的Operation
js的装饰器

</>复制代码

  1. js有自带的装饰器,可以用来修饰类和方法
例子 - 换衣服系统

</>复制代码

  1. 实现一个换衣服系统,一个人可以穿各种服饰,以一定顺序输出穿捉的服装
版本0

</>复制代码

  1. class Person0 {
  2. private name: string;
  3. constructor (name: string) {
  4. this.name = name
  5. }
  6. wearTShirts () {
  7. console.log(" T-shirts")
  8. }
  9. wearBigTrouser () {
  10. console.log(" big trouser")
  11. }
  12. wearSneakers () {
  13. console.log("sneakers ")
  14. }
  15. wearSuit () {
  16. console.log("suit")
  17. }
  18. wearLeatherShoes () {
  19. console.log("LeatherShoes")
  20. }
  21. show () {
  22. console.log(this.name)
  23. }
  24. }
  25. const person0 = new Person0("lujs")
  26. person0.wearBigTrouser()
  27. person0.wearTShirts()
  28. person0.wearSneakers()
  29. person0.wearSuit()
  30. person0.show()
版本1

上面的版本0,每次要添加不同的服饰,就需要修改person类,不符合开放-封闭原则,下面会抽离出服饰类,每个服饰子类都有添加服饰的方法,这样就解耦了person和finery

</>复制代码

  1. class Person1 {
  2. private name: string;
  3. constructor (name: string) {
  4. this.name = name
  5. }
  6. show () {
  7. console.log(this.name)
  8. }
  9. }
  10. abstract class Finery {
  11. abstract show (): void
  12. }
  13. class Tshirts extends Finery {
  14. show () {
  15. console.log(" T-shirts")
  16. }
  17. }
  18. class BigTrouser extends Finery {
  19. show () {
  20. console.log(" BigTrouser")
  21. }
  22. }
  23. class Sneakers extends Finery {
  24. show () {
  25. console.log(" Sneakers")
  26. }
  27. }
  28. // 调用
  29. const person1 = new Person1("lujs")
  30. const ts = new Tshirts()
  31. const bt = new BigTrouser()
  32. const sneakers = new Sneakers()
  33. person1.show()
  34. ts.show()
  35. bt.show()
  36. sneakers.show()
版本2

上面的版本1,多带带抽离了服饰类,这样就可以随意添加服饰而不会影响到person了,
但是在上面的调用代码中需要按顺序去调用自定服饰的show,最好就是只调用一次show就显示出正确的穿衣服顺序;需要把功能按正确的顺序进行控制,下面用装饰模式来实现实现

</>复制代码

  1. class Person2 {
  2. private name: string = ""
  3. setName (name: string) {
  4. this.name = name
  5. }
  6. show () {
  7. console.log("装扮", this.name);
  8. }
  9. }
  10. class Finery2 extends Person2 {
  11. private component: Person2 | null = null
  12. Decorator (component: Person2) {
  13. this.component = component
  14. }
  15. show () {
  16. if (this.component !== null) {
  17. this.component.show()
  18. }
  19. }
  20. }
  21. class Tshirts2 extends Finery2 {
  22. show () {
  23. super.show()
  24. console.log("穿tshirt");
  25. }
  26. }
  27. class BigTrouser2 extends Finery2 {
  28. show () {
  29. super.show()
  30. console.log("穿BigTrouser");
  31. }
  32. }
  33. const p2 = new Person2()
  34. const t1 = new Tshirts2()
  35. const b1 = new BigTrouser2()
  36. p2.setName("p2")
  37. t1.Decorator(p2)
  38. b1.Decorator(t1)
  39. b1.show()

</>复制代码

  1. 当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,
    比如用服饰装饰人,但这种做法的问题在于,它们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度
    而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。
    而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在多带带的类中,
    并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了
版本3

接下来我们使用js自带的装饰器来实现

</>复制代码

  1. class Person4 {
  2. private name: string = ""
  3. SetName (name: string) {
  4. this.name = name
  5. }
  6. show () {
  7. console.log("装备开始", this.name)
  8. }
  9. }
  10. // 装饰函数
  11. type fn = () => void
  12. function beforeShow(fns: fn[]) {
  13. return (target:any, name:any, descriptor:any) => {
  14. const oldValue = descriptor.value
  15. descriptor.value = function () {
  16. const value = oldValue.apply(this, arguments);
  17. fns.forEach(f:fn => {
  18. f()
  19. })
  20. return value
  21. }
  22. }
  23. }
  24. // 使用函数来代替服饰子类
  25. const wearTShirts = () => {
  26. console.log("wear Tshirts");
  27. }
  28. const wearBigTrouser = () => {
  29. console.log("wear BigTrouser");
  30. }
  31. class Finery4 extends Person4 {
  32. private person: Person4 | null = null
  33. addPerson (person: Person4) {
  34. this.person = person
  35. }
  36. @beforeShow([wearBigTrouser, wearTShirts])
  37. show () {
  38. if (this.person !== null) {
  39. this.person.show()
  40. }
  41. }
  42. }
  43. // 需要修改服饰顺序的时候,可以直接修改服饰类的装饰函数顺序,或者生成另一个类
  44. class Finery5 extends Person4 {
  45. private person: Person4 | null = null
  46. addPerson (person: Person4) {
  47. this.person = person
  48. }
  49. @beforeShow([wearTShirts, wearBigTrouser])
  50. show () {
  51. if (this.person !== null) {
  52. this.person.show()
  53. }
  54. }
  55. }
  56. const p6 = new Person4()
  57. const f6 = new Finery4()
  58. p6.SetName("lll")
  59. f6.addPerson(p6)
  60. f6.show()
  61. console.log("换一种服饰");
  62. const p7 = new Person4()
  63. const f7 = new Finery4()
  64. p7.SetName("lll")
  65. f7.addPerson(p7)
  66. f7.show()
表单例子 版本0

</>复制代码

  1. 一般我们写表单提交都会想下面那样先验证,后提交,
    但是submit函数承担了两个责任,验证和提交。
    我们可以通过装饰器把验证的方法剥离出来

</>复制代码

  1. const ajax = (url:string, data: any) => {console.log("ajax", url, data)}
  2. class Form {
  3. state = {
  4. username: "lujs",
  5. password: "lujs"
  6. }
  7. validata = ():boolean => {
  8. if (this.state.username === "") {
  9. return false
  10. }
  11. if (this.state.password === "") {
  12. return false
  13. }
  14. return true
  15. }
  16. submit = () => {
  17. if (!this.validata()) {
  18. return
  19. }
  20. ajax("url", this.state)
  21. }
  22. }
版本1

</>复制代码

  1. 先把验证函数多带带写成插件
    现在submit函数只有提交数据这个功能,而验证功能写成了装饰器

</>复制代码

  1. interface RequestData {
  2. username: string
  3. password: string
  4. }
  5. type Vality = (data: RequestData) => boolean
  6. type ValityFail = (data: RequestData) => void
  7. const validata = (data: RequestData):boolean => {
  8. if (data.username === "") {
  9. return false
  10. }
  11. if (data.password === "") {
  12. return false
  13. }
  14. console.log("验证通过")
  15. return true
  16. }
  17. function verify(vality:Vality, valityFail: ValityFail) {
  18. return (target:any, name:string, descriptor:any) => {
  19. const oldValue = descriptor.value
  20. descriptor.value = function (requestData: RequestData) {
  21. // 验证处理
  22. if (!vality(requestData)) {
  23. // 验证失败处理
  24. valityFail(requestData)
  25. return
  26. }
  27. // console.log(this, " == this")
  28. return oldValue.apply(this, arguments)
  29. }
  30. return descriptor
  31. }
  32. }
  33. class Form1 {
  34. state = {
  35. username: "",
  36. password: "password"
  37. }
  38. @verify(validata, () => console.log("验证失败"))
  39. submit(requestData: RequestData) {
  40. ajax("url", requestData)
  41. }
  42. }
  43. console.log("表单验证例子1开始---")
  44. const f1 = new Form1
  45. f1.submit(f1.state)
  46. f1.state.username = "lujs"
  47. f1.submit(f1.state)
  48. console.log("表单验证例子1结束---")

#### 版本2

</>复制代码

  1. 把验证器写成多带带的插件

</>复制代码

  1. /**
  2. * 一个使用装饰功能的表单验证插件
  3. */
  4. // 先定义一下希望插件的调用方式, 输入一个数组,内容可以是字符串或者对象
  5. state = {
  6. username: "lujs",
  7. myEmail: "123@qq.com",
  8. custom: "custom"
  9. }
  10. @validate([
  11. "username", // fail: () =>console.log("username wrong")
  12. {
  13. key: "myEmail",
  14. method: "email"
  15. },
  16. {
  17. key: "myEmail",
  18. method: (val) => val === "custom",
  19. fail: () => alert("fail")
  20. }
  21. ])
  22. submit(requestData: RequestData) {
  23. ajax("url", requestData)
  24. }

./validator.ts

</>复制代码

  1. export interface Validator {
  2. notEmpty (val: string):boolean
  3. notEmail (val: string):boolean
  4. }
  5. export const validator: Validator = {
  6. notEmpty: (val: string) => val !== "",
  7. notEmail: (val: string) => !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(val)
  8. }
  9. export interface V {
  10. key: string
  11. method: keyof Validator | ((val: any) => boolean)
  12. fail?: (val: any) => void
  13. }
  14. export function verify(
  15. vality: Array,
  16. ) {
  17. return (target:any, propertyKey:string, descriptor:PropertyDescriptor) => {
  18. const oldValue = descriptor.value
  19. descriptor.value = function (requestData: {[p: string]: any}) {
  20. // 验证处理
  21. const flag = vality.every((v) => {
  22. console.log(typeof v, v, " == this")
  23. if (typeof v === "string") {
  24. const val = requestData[v]
  25. // 默认进行empty判断
  26. if (!validator.notEmpty(val)) {
  27. return false
  28. }
  29. } else {
  30. // 对象的情况
  31. const val = requestData[v.key]
  32. console.log(val, " => val")
  33. console.log(v, " => v")
  34. if (typeof v.method === "string") {
  35. if (!validator[v.method](val)) {
  36. if (v.fail) {
  37. v.fail.apply(this, requestData)
  38. }
  39. return false
  40. }
  41. } else {
  42. console.log(v.method(val), val)
  43. if (!v.method(val)) {
  44. if (v.fail) {
  45. v.fail.apply(this, requestData)
  46. }
  47. return false
  48. }
  49. }
  50. }
  51. return true
  52. })
  53. if (!flag) {
  54. return
  55. }
  56. return oldValue.apply(this, arguments)
  57. }
  58. return descriptor
  59. }
  60. }

./form

</>复制代码

  1. import {verify} from "./validator"
  2. const ajax = (url:string, data: any) => {console.log("ajax", url, data)}
  3. class Form2 {
  4. state = {
  5. username: "lujs",
  6. myEmail: "123@qq.com",
  7. custom: "custom"
  8. }
  9. @verify([
  10. "username", // fail: () =>console.log("username wrong")
  11. {
  12. key: "myEmail",
  13. method: "notEmail"
  14. },
  15. {
  16. key: "myEmail",
  17. method: (val) => val !== "custom",
  18. fail: (val) => console.log(val)
  19. }
  20. ])
  21. submit(requestData: {[p: string]: any}) {
  22. ajax("url", requestData)
  23. }
  24. }
  25. const f2 = new Form2
  26. f2.submit(f2.state)

例子来自《大话设计模式》《javascript设计模式与开发实践》

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/98372.html

相关文章

  • [译] Angular 的 @Host 装饰器和元素注入器

    摘要:装饰器我们为啥要讨论元素注入器而不是装饰器这是因为会把元素注入器依赖解析过程限制在当前组件视图内。但是一旦使用了装饰器,整个依赖解析过程就会在第一阶段完成后停止解析,也就是说,元素注入器只在组件视图内解析依赖,然后就停止解析工作。 原文链接:A curious case of the @Host decorator and Element Injectors in Angular 我...

    marek 评论0 收藏0
  • 从ES6重新认识JavaScript设计模式: 装饰模式

    摘要:什么是装饰器模式向一个现有的对象添加新的功能,同时又不改变其结构的设计模式被称为装饰器模式,它是作为现有的类的一个包装。中的装饰器模式中有一个的提案,使用一个以开头的函数对中的及其属性方法进行修饰。 1 什么是装饰器模式 showImg(https://segmentfault.com/img/remote/1460000015970102?w=1127&h=563); 向一个现有的对...

    wendux 评论0 收藏0
  • 学学AOP之装饰模式

    摘要:但是,这样做的后果就是,我们会不断的改变本体,就像把凤姐送去做整形手术一样。在中,我们叫做引用装饰。所以,这里引入的装饰模式装饰亲切,熟悉,完美。实例讲解装饰上面那个例子,只能算是装饰模式的一个不起眼的角落。 装饰者,英文名叫decorator. 所谓的装饰,从字面可以很容易的理解出,就是给 土肥圆,化个妆,华丽的转身为白富美,但本体还是土肥圆。 说人话.咳咳~ 在js里面一切都是对...

    nihao 评论0 收藏0
  • JavaScript装饰模式

    摘要:用户名不能为空密码不能为空校验未通过使用优化代码返回的情况直接,不再执行后面的原函数用户名不能为空密码不能为空 本文是《JavaScript设计模式与开发实践》的学习笔记,例子来源于书中,对于设计模式的看法,推荐看看本书作者的建议。 什么是装饰者模式? 给对象动态增加职责的方式成为装饰者模式。 装饰者模式能够在不改变对象自身的基础上,在运行程序期间给对象动态地添加职责。这是一种轻便灵活...

    Taste 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<