设计模式之装饰器模式
程序员文章站
2024-02-26 19:49:46
...
装饰器模式:根据一个基本的对象,可以动态的对他进行改造,扩展功能,这里强调的是自定义扩展,注意和工厂模式进行区分
核心在于,实现Compent的那个基本对象的构造方法,由于继承,实现的关系都间接实现了Compent接口,然后通过装饰器对构造器中传入的对象进行扩展,需要什么功能调取什么装饰器就可以。通过这种模式可以实现自定义的扩展对象功能
类图:
AdminDecorator
package decorator;
public class AdminDecorator extends NavbarDecorator{
public AdminDecorator(Navbar decoratedNavbar) {
super(decoratedNavbar);
}
@Override
public void base() {
super.base();
//扩展功能
addBar();
}
private void addBar() {
System.out.println("+ 管理员栏位!");
}
}
BaseNavbar:
package decorator;
public class BaseNavbar implements Navbar {
@Override
public void base() {
System.out.println("导航栏 基本栏位!");
}
}
GuestDecorator:
package decorator;
public class GuestDecorator extends NavbarDecorator{
public GuestDecorator(Navbar decoratedNavbar) {
super(decoratedNavbar);
}
@Override
public void base() {
super.base();
//扩展功能
addBar();
}
private void addBar() {
System.out.println(" + 游客栏位!");
}
}
Navbar:
package decorator;
public class GuestDecorator extends NavbarDecorator{
public GuestDecorator(Navbar decoratedNavbar) {
super(decoratedNavbar);
}
@Override
public void base() {
super.base();
//扩展功能
addBar();
}
private void addBar() {
System.out.println(" + 游客栏位!");
}
}
NavbarDecorator:
package decorator;
public abstract class NavbarDecorator implements Navbar {
protected Navbar decoratedNavbar;
public NavbarDecorator(Navbar decoratedNavbar){
super();
this.decoratedNavbar = decoratedNavbar;
}
@Override
public void base() {
decoratedNavbar.base();
}
}
test:
package decorator;
public class test {
public static void main(String[] args) {
Navbar bar = new BaseNavbar();
System.out.println("========无装饰=========");
bar.base();
Navbar adminDecorator = new AdminDecorator(bar);
System.out.println("========管理员装饰=========");
adminDecorator.base();
System.out.println("=========经过管理员装饰 + 游客装饰=========");
Navbar guestNabar = new GuestDecorator(adminDecorator);
guestNabar.base();
}
}
运行结果:
上一篇: 设计模式笔记2-策略模式