裝飾器模式

2022-02-26 23:00:19 字數 2709 閱讀 9070

1.簡介

裝飾器模式(decorator pattern)允許向乙個現有的物件新增新的功能,同時又不改變其結構。這種型別的設計模式屬於結構型模式,它是作為現有的類的乙個包裝。

這種模式建立了乙個裝飾類,用來包裝原有的類,並在保持類方法簽名完整性的前提下,提供了額外的功能。

我們模擬遊戲角色進行裝飾器模式的學習

在這個遊戲中,我們新建乙個角色,並使用裝飾器模式獲取各種裝備

先新建乙個基礎特徵類(餘下所有類都繼承這個類或者繼承 繼承這個類的類)

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern

}

新增乙個新建法師角色的功能

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern

}}

新增乙個裝飾器類

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern.decorator

public

override

void

show()

}}

新增裝備類1-4

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern.decorator

public

override

void

show()

}}

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern.decorator

public

override

void

show()

}}

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern.decorator

public

override

void

show()

}}

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern.decorator

public

override

void

show()

}}

使用裝飾器模式

program:

using

decoratorpattern.decorator;

using

system;

using

system.collections.generic;

using

system.linq;

using

system.text;

using

system.threading.tasks;

namespace

decoratorpattern

}}

裝飾器模式

大話設計模式 裝飾器模式 為已有功能動態地新增更多功能,當系統需要新功能,向舊的類中新增新功能,裝飾了原有類的核心職責和行為,而不改變它們 就像包裝袋一樣,有 的包裝袋包裝之前裝好東西的包裝袋 ifndef clothes h define clothes h include using names...

裝飾器模式

裝飾器設計模式 對真實物件動態的新增功能 抽象元件 author zhangjianbin public inte ce icar 俱體構件物件 真實的物件 author zhangjianbin class car implements icar 裝飾器物件 author zhangjianbin...

裝飾器模式

一 概念 裝飾模式能夠實現動態的為物件新增功能,是從乙個物件外部來給物件新增功能。通常給物件新增功能,要麼直接修改物件新增相應的功能,要麼派生對應的子類來擴充套件,抑或是使用物件組合的方式。顯然,直接修改對應的類這種方式並不可取。在物件導向的設計中,而我們也應該 盡量使用物件組合,而不是物件繼承來擴...