-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
``` | ||
|
||
|
||
|