美文网首页
设计模式-装饰模式

设计模式-装饰模式

作者: 探索者_逗你玩儿 | 来源:发表于2018-10-17 23:23 被阅读0次

    装饰模式:动态的给对象扩展功能,提供了比继承更为弹性的替代方案。详情看代码

    
    /**
     * 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());
    
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式-装饰模式

          本文链接:https://www.haomeiwen.com/subject/sdudzftx.html