zoukankan      html  css  js  c++  java
  • 设计模式-状态模式

    (#)原因

    本来不想写设计模式的东西,因为我觉得这个谁都懂,我们每天在写代码的时候,不知不觉就在使用设计模式,但是最近接了一些新的项目,在维护老代码的时候

    发现各种问题,代码很烂,及其难扩展,遂看了重构,发现要想看懂这本书必须要熟悉各种设计模式,所以开始写设计模式系列博客

    (#)状态模式

    当一个对象的行为,取决与他的状态的时候,最适合使用这种方式写代码,比如一个对象的属性发生改变的时候,那么这个对象的同一个方法表现出来的动作是不一样的,

    talk is cheap show you the code

    (#)code

    首先我们定义一个抽象类

    public abstract class Price {
        private double money;
    
        public Price() {
        }
    
        public Price(double money) {
            this.money = money;
        }
    
        public double getMoney() {
            return money;
        }
    
        public void setMoney(double money) {
            this.money = money;
        }
    
        abstract double getChange(int days);
    }
    

    其次定义两个状态类

    /**
     * Author: scw
     * Time: 16-11-22
     */
    public class ChildPrice extends Price {
        public ChildPrice() {
        }
    
        public ChildPrice(double money) {
            super(money);
        }
    
        @Override
        double getChange(int days) {
            return super.getMoney()*days*2;
        }
    }
    

     

    /**
     * Author: scw
     * Time: 16-11-22
     */
    public class RegularPrice extends Price {
        public RegularPrice() {
        }
    
        public RegularPrice(double money) {
            super(money);
        }
    
        @Override
        double getChange(int days) {
            return super.getMoney()*4*days;
        }
    }
    

     最后我们定义一个主体类来承载这个状态

    /**
     * Author: scw
     * Time: 16-11-22
     */
    public class Movie {
        private Price price;
    
        public Movie(Price price) {
            this.price = price;
        }
    
        public double getChange(int days){
            return price.getChange(days);
        }
    }
    

    最后写一个main方法跑跑看:

     public static void main(String[]args){
            ChildPrice childPrice = new ChildPrice(1.1);
            RegularPrice regularPrice = new RegularPrice(1.1);
            Movie movie = new Movie(childPrice);
            System.out.println(movie.getChange(1));
            movie = new Movie(regularPrice);
            System.out.println(movie.getChange(1));
        }
    

    这么实现的代码之后,其实完全符合设计模式的单一原则,里氏替换原则,以及开闭原则,很容易扩展以及维护

      

  • 相关阅读:
    软件开发过程须贯彻评估和测试
    【灌水】多维成功论
    改进c系列(目录)
    网站管理艺术
    .net 跨平台也是一句谎言
    用户界面和逻辑应该分离
    设计模式
    程序员找不到工作是因为管理差
    编码阶段
    保证软件开发质量的一种管理学
  • 原文地址:https://www.cnblogs.com/wscit/p/6091529.html
Copyright © 2011-2022 走看看