Java設計模式之裝飾者模式詳解
裝飾器模式(Decorator Pattern
)允許向一個現(xiàn)有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬于結構型模式,它是作為現(xiàn)有的類的一個包裝。
以一個Person對象為例。Person作為一個接口,Student(學生)和Doctor(醫(yī)生)為Person接口的兩個具體類,DecoratorPerson為Person的裝飾類,可對具體類進行裝飾。ShoeDecorator(鞋子裝飾類)和DressDecorator(衣服裝飾類)為具體的裝飾類。這個案例可對學生和醫(yī)生進行裝飾。
具體代碼:
Person:
public interface Person { void description(); }
Student:
public class Student implements Person { @Override public void description() { System.out.println("學生"); } }
Doctor:
public class Doctor implements Person { @Override public void description() { System.out.println("醫(yī)生"); } }
DecoratePerson:
public class DecoratePerson implements Person { private Person person; public DecoratePerson(Person person) { this.person = person; } @Override public void description() { person.description(); } }
ShoeDecorate:
public class ShoeDecorate extends DecoratePerson { public ShoeDecorate(Person person) { super(person); } @Override public void description() { super.description(); System.out.println("穿鞋子"); } }
DressDecorate:
public class DressDecorate extends DecoratePerson { public DressDecorate(Person person) { super(person); } @Override public void description() { super.description(); System.out.println("穿衣服"); } }
測試類:根據(jù)裝飾的順序和對象不同,呈現(xiàn)不同的結果和順序
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
在SpringBoot中注入RedisTemplate實例異常的解決方案
這篇文章主要介紹了在SpringBoot中注入RedisTemplate實例異常的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01IDEA?一直scanning?files?to?index的四種完美解決方法(VIP典藏版)
這篇文章主要介紹了IDEA?一直scanning?files?to?index的四種完美解決方法(VIP典藏版),推薦第四種方法,第四種方法摸索研究后得出,親測好用,需要的朋友參考下吧2023-10-10這一次搞懂Spring代理創(chuàng)建及AOP鏈式調用過程操作
這篇文章主要介紹了這一次搞懂Spring代理創(chuàng)建及AOP鏈式調用過程操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08JAVA 16位ID生成工具類含16位不重復的隨機數(shù)數(shù)字+大小寫
這篇文章主要介紹了JAVA 16位ID生成工具類含16位不重復的隨機數(shù)數(shù)字+大小寫,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02修改Maven settings.xml 后配置未生效的解決
這篇文章主要介紹了修改Maven settings.xml 后配置未生效的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10