您的位置:首页 > 其它

设计模式-状态模式

2016-11-22 22:50 169 查看
(#)原因

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

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

(#)状态模式

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

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));
}


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

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: