的给一个对象添加一些的功能 。


/**
-
@Author: cxh
-
@CreateTime: 18/1/2 21:20
-
@ProjectName: JavaBaseTest
*/
public class Person {
private String name;
Person(){}//子类实例化时,默认调用父类的无参数构造器方法.如果没有这个方法,则编译报错.
Person(String name){
this.name=name;
}
public void operation(){
System.out.println("this is :"+name);
}
}
/**
-
@Author: cxh
-
@CreateTime: 18/1/2 21:22
-
@ProjectName: JavaBaseTest
*/
public class Decorator extends Person {
protected Person person;
Decorator(){}
public void decorator(Person person){
this.person=person;
}
@Override
public void operation() {
if(person!=null)
person.operation();
}
}
/**
- @Author: cxh
- @CreateTime: 18/1/2 21:31
- @ProjectName: JavaBaseTest
*/
public class TShirts extends Decorator {
@Override
public void operation() {
super.operation();
//调用自己的方法
funcSelf();
}
private void funcSelf(){
System.out.println("衬衫");
}
}
/**
- @Author: cxh
- @CreateTime: 18/1/2 21:35
- @ProjectName: JavaBaseTest
*/
public class Pants extends Decorator {
@Override
public void operation() {
super.operation();
//调用自己的方法
funcSelf();
}
private void funcSelf(){
System.out.println("西裤");
}
}
/**
- @Author: cxh
- @CreateTime: 18/1/2 21:36
- @ProjectName: JavaBaseTest
*/
public class Shoes extends Decorator {
@Override
public void operation() {
super.operation();
//调用自己的方法
funcSelf();
}
private void funcSelf(){
System.out.println("高跟鞋");
}
}
/**
-
@Author: cxh
-
@CreateTime: 18/1/2 21:38
-
@ProjectName: JavaBaseTest
*/
public class Client {
//测试类
public static void main(String[] args) {
Person person=new Person("朱莉");
TShirts tShirts=new TShirts();
Pants pants=new Pants();
Shoes shoes=new Shoes();
tShirts.decorator(person);
pants.decorator(tShirts);
shoes.decorator(pants);
shoes.operation();
}
}
输出:
Process finished with exit code 0
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|