java装饰者模式源代码_装饰者模式(Decoration)_java实现
//20210118写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现装饰者模式核心思想:构建一个带有原始属性的对象,然后通过附加类来一层一层的装饰原有对象源代码如下://初始接口public interface Man {String getDes();}//带有初始属性的类public class NormalMan implements Man
//20210118
写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现装饰者模式
核心思想:
构建一个带有原始属性的对象,然后通过附加类来一层一层的装饰原有对象
源代码如下:
//初始接口
public interface Man {
String getDes();
}
//带有初始属性的类
public class NormalMan implements Man{
private String name;
public NormalMan(String name){
this.name = name;
}
@Override
public String getDes() {
return name + ":";
}
}
//抽象装饰类
public abstract class AttachedPropertiesDecorator implements Man{
private Man man;
public AttachedPropertiesDecorator(Man man){
this.man = man;
}
@Override
public String getDes() {
return man.getDes();
}
}
//实现装饰类1
public class CarDecorator extends AttachedPropertiesDecorator{
private String car = "有车";
public CarDecorator(Man man) {
super(man);
}
public String addCar(){
return this.car+" ";
}
@Override
public String getDes() {
return super.getDes()+this.addCar();
}
}
//实现装饰类2
public class DepositeDecorator extends AttachedPropertiesDecorator{
private String deposite = "有存款";
public DepositeDecorator(Man man) {
super(man);
}
public String addDeposite(){
return this.deposite+" ";
}
@Override
public String getDes() {
return super.getDes() + this.addDeposite();
}
}
//实现装饰类3
public class HouseDecorator extends AttachedPropertiesDecorator{
private String house = "有房";
public HouseDecorator(Man man) {
super(man);
}
public String addHouse(){ return this.house+" ";
}
@Override
public String getDes() {
return super.getDes() + this.addHouse();
}
}
//实现装饰类4
public class QualityDecorator extends AttachedPropertiesDecorator{
private String quality = "有好品质";
public QualityDecorator(Man man) {
super(man);
}
public String addQuality(){
return this.quality+" ";
}
@Override
public String getDes() {
return super.getDes() + this.addQuality();
}
}
//测试主类
public class Main {
public static void main(String[] args) {
Man man= new NormalMan("张三");
System.out.println(man.getDes());
man = new CarDecorator(man);//加入车属性
System.out.println(man.getDes());
man = new DepositeDecorator(man);//加入存款属性
System.out.println(man.getDes());
man = new HouseDecorator(man);//加入房屋属性
System.out.println(man.getDes());
man = new QualityDecorator(man);//加入房屋属性
System.out.println(man.getDes());
}
}
输出如下:
以上
希望对大家有所帮助
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)