1.策略模式
策略模式,用于算法计算比较多,抽象出一个计算的接口。
//1.接口策略计算类
public interface Calulator{
int calulator(int price);
}
//2.产品类
public class Proudct{
private Calulator cal;
private int originalPrice;
public Product(int price){
this.originalPrice = price;
}
public void setCal(Calulator cal){
this.cal = cal;
}
public int calulatorPrice(){
return cal.calulator(originalPrice);
}
}
//3.具体的策略实现类
public class StragetyA implements Calulator{
@Override
public int calulator(int price){
return (int)(price*0.9);
}
}
public class StragetyB implements Calulator{
@Override
public int calulator(int price){
return price-20;
}
}
//4.客户端调用
public class Client{
public static void main(String[] args){
Product product = new Product(2000);
Calulator sa = new StragetyA ();
Calulator sb = new StragetyB ();
//用策略A计算价格
product.setCal(sa);
product.calulatorPrice();
//用策略B计算价格
product.setCal(sb);
product.calulatorPrice();
}
}
2.状态模式
电视机的状态开机关机上一频道下一频道
//1.抽象的状态接口
public interface TvState{
void nextChannel();
void preChannel();
void turnOn();
void turnOff();
}
//2.具体状态类
public class PowerOff implements TVState{
@Override
public void nextChannel() {
System.out.println("关机 无效");
}
@Override
public void preChannel() {
System.out.println("关机 无效");
}
@Override
public void turnOn() {
System.out.println("开机");
}
@Override
public void turnOff() {
System.out.println("关机 无效");
}
}
public class PowerOn implements TVState{
@Override
public void nextChannel() {
System.out.println("下一频道");
}
@Override
public void preChannel() {
System.out.println("上一频道");
}
@Override
public void turnOn() {
System.out.println("正在开机");
}
@Override
public void turnOff() {
System.out.println("关机");
}
}
//3.Tv控制的上下文环境
public class TvContext {
private TVState tvState=new PowerOff();
public void setTate(TVState tvState){
this.tvState=tvState;
}
public void turnOn(){
setTate(new PowerOn());
tvState.turnOn();
}
public void turnOff(){
setTate(new PowerOff());
tvState.turnOff();
}
public void nextChannel(){
tvState.nextChannel();
}
public void preChannel() {
tvState.preChannel();
}
}
//4.客户端调用
public class Client {
public static void main(String[] args) {
TvContext tvContext=new TvContext();
tvContext.nextChannel();
tvContext.turnOff();
tvContext.turnOn();
tvContext.nextChannel();
tvContext.preChannel();
}
}
策略模式一个接口方法进行计算,状态模式抽象出几个状态。
具体的状态重接口中进行控制。
状态模式的控制上下文环境中持有具体状态的应用,上下文的环境中包括状态控制方法。
通过Context设置控制状态,进行控制。真正的控制是在状态实现类当中。