上海网站建设哪个平台好,招聘网站开发流程,网站中怎么做下载链接,主机 wordpress一、前言
1.1 背景
针对某种业务可能存在多种实现方式#xff0c;传统方式是通过传统if…else…或者switch代码判断#xff1b;
弊端#xff1a;
代码可读性差扩展性差难以维护
1.2 简介
策略模式是一种行为型模式#xff0c;它将对象和行为分开#xff0c;将行为定…一、前言
1.1 背景
针对某种业务可能存在多种实现方式传统方式是通过传统if…else…或者switch代码判断
弊端
代码可读性差扩展性差难以维护
1.2 简介
策略模式是一种行为型模式它将对象和行为分开将行为定义为一个行为接口和具体行为的实现。
组成
抽象策略类(Strategy)策略的抽象具体策略类(ConcreteStrategy)具体的策略实现环境类(Context)用来操作策略的上下文环境
二、案例代码
此处以Iphone的制造商举例抽象策略类(IphoneProducer)具体策略类(ChinaIphoneProducer、VietnamIphoneProducer、USAIphoneProducer)环境类(ProducerContext)
package com.qiangesoft.design.behavioral.strategy;/*** 策略模式*/
public class Strategy {public static void main(String[] args) {ProducerContext context new ProducerContext();// 中国context.setProducer(new ChinaIphoneProducer());System.out.println(Made in context.produce().getProducer());// 越南context.setProducer(new VietnamIphoneProducer());System.out.println(Made in context.produce().getProducer());// 美国context.setProducer(new USAIphoneProducer());System.out.println(Made in context.produce().getProducer());}
}/*** 1.策略接口* 此处Iphone制造商*/
interface IphoneProducer {/*** 生产*/Iphone produce();
}/*** 2.策略实现类* 中国制造商、越南制造商、美国制造商*/
class ChinaIphoneProducer implements IphoneProducer {Overridepublic Iphone produce() {return new Iphone(China);}
}class VietnamIphoneProducer implements IphoneProducer {Overridepublic Iphone produce() {return new Iphone(Vietnam);}
}class USAIphoneProducer implements IphoneProducer {Overridepublic Iphone produce() {return new Iphone(USA);}
}/*** 3.环境类*/
class ProducerContext {private IphoneProducer producer;public void setProducer(IphoneProducer producer) {this.producer producer;}public Iphone produce() {return producer.produce();}
}/*** 苹果手机*/
class Iphone {/*** 制造商*/private String producer;public Iphone(String producer) {this.producer producer;}public String getProducer() {return producer;}public void setProducer(String producer) {this.producer producer;}
}三、总结
优点
切换算法方便避免大量的条件语句提高代码的复用性降低耦合度
缺点
策略类过多类爆炸客户端必须了解所有的策略类策略模式的对象数量过多占用更多的内存空间