Skip to content

Commit

Permalink
增加装饰者模式
Browse files Browse the repository at this point in the history
  • Loading branch information
VentureQ committed Jul 9, 2021
1 parent d756dc0 commit a61c319
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions 23种设计模式/装饰者模式的概念及Java实现.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
​ 装饰者模式(Decorator Pattern)是指在无需改变原有类以及类的继承关系的情况下,动态扩展一个类的功能。它通过装饰者来包裹真实的对象,并动态的向对象添加或者撤销功能。

定义Sourceable接口:

```java
public interface Sourceable {
public void createComputer();
}
```

定义Sourceable接口的实现类:

```java
public class Source implements Sourceable{
@Override
public void createComputer() {
System.out.println("create computer by Source.");
}
}
```

定义装饰者Decorator类:

```java
public class Decorator implements Sourceable{
private Sourceable source;

public Decorator(Sourceable source) {
this.source = source;
}

@Override
public void createComputer() {
source.createComputer();
System.out.println("make system.");
}
}
```

使用装饰者模式:

```java
public class Test {
public static void main(String[] args) {
Sourceable source=new Source();
Sourceable obj=new Decorator(source);
obj.createComputer();
}
}
```



0 comments on commit a61c319

Please sign in to comment.