装饰模式:动态的给对象扩展功能,提供了比继承更为弹性的替代方案。详情看代码
/**
* Created by apple on 2018/10/17.
*/
public interface CarService {
public double takeCosts();
public String takeServiceName();
}
/**
* Created by apple on 2018/10/17.
*/
public abstract class CommonService implements CarService {
protected CarService carService;
public CommonService(CarService carService) {
this.carService = carService;
}
}
/**
* Created by apple on 2018/10/17.
*/
public class MetaSheetService extends CommonService {
public MetaSheetService(CarService carService) {
super(carService);
}
@Override
public double takeCosts() {
return carService.takeCosts()+ 135.0;
}
@Override
public String takeServiceName() {
return carService.takeServiceName()+ ","+ "钣金";
}
}
/**
* Created by apple on 2018/10/17.
*/
public class RefitService extends CommonService {
public RefitService(CarService carService) {
super(carService);
}
@Override
public double takeCosts() {
return carService.takeCosts()+ 235.0;
}
@Override
public String takeServiceName() {
return carService.takeServiceName()+ "," + "改装";
}
}
/**
* Created by apple on 2018/10/17.
*/
public class WashCarService implements CarService {
@Override
public double takeCosts() {
return 30.0;
}
@Override
public String takeServiceName() {
return "洗车";
}
}
/**
* Created by apple on 2018/10/17.
*/
public class Main {
public static void main(String[] args){
WashCarService washCarService = new WashCarService();
System.out.println(washCarService.takeCosts());
System.out.println(washCarService.takeServiceName());
MetaSheetService metaSheetService = new MetaSheetService(washCarService);
System.out.println(metaSheetService.takeCosts());
System.out.println(metaSheetService.takeServiceName());
RefitService refitService = new RefitService(metaSheetService);
System.out.println(refitService.takeCosts());
System.out.println(refitService.takeServiceName());
}
}
网友评论