文章目录
前言
学习总结吧,参考了 GOF 设计模式以及网上许多例子,实际上也就是个代码+流程图重新排码,方便后续查阅理解
设计模式
创建型
抽象工厂模式
////////////////////////////////////////////////////////////////////////////
// 产品接口 1
interface IProduct1 {
public void show();
}
// 产品接口 2
interface IProduct2 {
public void show();
}
// 产品实现 1
class Product1 implements IProduct1 {
public void show() {
System.out.println("这是1型产品");
}
}
// 产品实现 2
class Product2 implements IProduct2 {
public void show() {
System.out.println("这是2型产品");
}
}
////////////////////////////////////////////////////////////////////////////
// 工厂接口
interface IFactory {
public IProduct1 createProduct1();
public IProduct2 createProduct2();
}
// 工厂实现
class Factory implements IFactory{
public IProduct1 createProduct1() {
return new Product1();
}
public IProduct2 createProduct2() {
return new Product2();
}
}
////////////////////////////////////////////////////////////////////////////
// 调用
public class Client {
public static void main(String[] args){
IFactory factory = new Factory();
factory.createProduct1().show();
factory.createProduct2().show();
}
}
单例模式
饿汉式
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}
懒汉式
public class Singleton {
private static Singleton singleton;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
工厂方法模式
简单工厂:
/////////////////////////////////////////////////////////////////////////////
// 抽象产品角色
interface Fruit{ // 定义一个水果接口
public void eat() ; // 吃水果
}
// 具体产品角色 1
class Apple implements Fruit{
public void eat(){
System.out.println("** 吃苹果。") ;
}
};
// 具体产品角色 2
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子。") ;
}
};
/////////////////////////////////////////////////////////////////////////////
// 工厂角色
class Factory{ // 定义工厂类
public static Fruit getInstance(String className){
Fruit f = null ;
if("apple".equals(className)){ // 判断是否要的是苹果的子类
f = new Apple() ;
}
if("orange".equals(className)){ // 判断是否要的是橘子的子类
f = new Orange() ;
}
return f ;
}
};
///////////////////////////////////////////////////////////////////////////
// 测试
public class InterfaceCaseDemo05{
public static void main(String args[]){
// 通过传入的名称来创建实例
Fruit f = Factory.getInstance(args[0]) ; // 实例化接口
if(f!=null){ // 判断是否取得实例
f.eat() ;
}
}
};
工厂方法
////////////////////////////////////////////////////////////////////////////////////////
// 产品接口角色
interface IProduct {
public void productMethod();
}
// 产品实现 1
class Product1 implements IProduct {
public void productMethod() {
System.out.println("产品1");
}
}
// 产品实现 2
class Product2 implements IProduct {
public void productMethod() {
System.out.println("产品2");
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 工厂接口角色
interface IFactory {
public IProduct createProduct();
}
// 工厂 1
class Factory1 implements IFactory {
public IProduct createProduct() {
return new Product1();
}
}
// 工厂 2
class Factory2 implements IFactory {
public IProduct createProduct() {
return new Product2();
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args) {
IFactory factory = new Factory1();
IProduct prodect = factory.createProduct();
prodect.productMethod();
}
}
建造者模式
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////////
// 产品类
class Product
{
vector<string> parts; // 动态数组
public:
void Add(const string part)
{
parts.push_back(part);
}
void Show()const
{
for(int i = 0 ; i < parts.size() ; i++)
{
cout<<parts[i]<<endl;
}
}
};
//////////////////////////////////////////////////////////////////////////////////////////
// 抽象建造者
class Builder
{
public:
///////////////////////////////////////////////////////////////
// 组装过程
virtual void BuildHead() = 0;
virtual void BuildBody() = 0;
virtual void BuildHand() = 0;
virtual void BuildFeet() = 0;
virtual Product GetResult() = 0;
};
//具体建造类:胖人
class FatPersonBuilder :public Builder
{
private:
Product product;
public:
//////////////////////////////////////////////////////////////
// 组装过程
virtual void BuildHead()
{
product.Add("胖人头");//创建胖人的头
}
virtual void BuildBody()
{
product.Add("胖人身体");//创建胖人的身体
}
virtual void BuildHand()
{
product.Add("胖人手");//创建胖人的手
}
virtual void BuildFeet()
{
product.Add("胖人脚");//创建胖人的脚
}
/////////////////////////////////////////////////////////////
// 获得产品
virtual Product GetResult()
{
return product;
}
};
//具体建造类:瘦人
class ThinPersonBuilder :public Builder
{
private:
Product product;
public:
//////////////////////////////////////////////////////////////
// 组装过程
virtual void BuildHead()
{
product.Add("瘦人人头");//创建瘦人的头
}
virtual void BuildBody()
{
product.Add("瘦人身体");//创建瘦人的身体
}
virtual void BuildHand()
{
product.Add("瘦人手");//创建瘦人的手
}
virtual void BuildFeet()
{
product.Add("瘦人脚");//创建瘦人的脚
}
/////////////////////////////////////////////////////////////
// 获得产品
virtual Product GetResult()
{
return product;
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// 导演类
class Director
{
public:
void Construct(Builder &builder)
{
builder.BuildHead();
builder.BuildBody();
builder.BuildHand();
builder.BuildFeet();
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// 测试
int main()
{
Director *director = new Director();
Builder *b1 = new FatPersonBuilder();
Builder *b2 = new ThinPersonBuilder();
// 通过导演类按指定步骤组装
director->Construct(*b1);
// 通过建造类获得产品
Product p1 = b1->GetResult();
p1.Show();
return 0;
}
原型模式
/////////////////////////////////////////////////////////////////////////////////////////
// 原型类
public class Prototype implements Cloneable {
private ArrayList list = new ArrayList();
public Prototype clone(){
Prototype prototype = null;
try{
prototype = (Prototype)super.clone();
prototype.list = (ArrayList) this.list.clone(); // 注意深,浅拷贝:ArrayList不是基本类型,所以成员变量list,不会被拷贝,需要我们自己实现深拷贝
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return prototype;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// 原型类实现
class ConcretePrototype extends Prototype{
public void show(){
System.out.println("原型模式实现类");
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// 调用类
public class Client {
public static void main(String[] args){
ConcretePrototype cp = new ConcretePrototype();
for(int i=0; i< 10; i++){
ConcretePrototype clonecp = (ConcretePrototype)cp.clone();// 关键在这个 clone() 函数,子类是没有实现的,是父类实现的
clonecp.show();
}
}
}
结构型
备忘录模式
单记录:
//////////////////////////////////////////////////////////////////////////////////////
// 发起人角色:需要被备份的类
class Originator {
////////////////////////////////////////////
// 需要备份的数据
private String state = "";
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
// 创建备忘录
public Memento createMemento(){
// 以当前状态创建了备忘录实例
return new Memento(this.state);
}
// 恢复备忘录
public void restoreMemento(Memento memento){
// 从备忘录实例中恢复状态
this.setState(memento.getState());
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 备忘录角色:保存所有需要备份的数据
class Memento {
//////////////////////////////////////////
// 备份数据保存的地方
private String state = "";
public Memento(String state){
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 管理者角色:管理备忘录实例的
class Caretaker {
//////////////////////////////////////
// 备忘录保存的地方
private Memento memento;
public Memento getMemento(){
return memento;
}
public void setMemento(Memento memento){
this.memento = memento;
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args){
// 初始化发起人状态
Originator originator = new Originator();
originator.setState("状态1");
System.out.println("初始状态:"+originator.getState());
// 初始化管理者备份
Caretaker caretaker = new Caretaker();
caretaker.setMemento(originator.createMemento()); // 管理者管理备份录角色
// 修改发起人状态
originator.setState("状态2");
System.out.println("改变后状态:"+originator.getState());
// 通过管理者获得备忘录实例,恢复发起者状态
originator.restoreMemento(caretaker.getMemento());
System.out.println("恢复后状态:"+originator.getState());
}
}
多记录:
//////////////////////////////////////////////////////////////////////////////////////
// 发起人角色:需要被备份的类
class Originator {
///////////////////////////////////////////////
// 要被保存的数据
private String state1 = "";
private String state2 = "";
private String state3 = "";
public String getState1() {
return state1;
}
public void setState1(String state1) {
this.state1 = state1;
}
public String getState2() {
return state2;
}
public void setState2(String state2) {
this.state2 = state2;
}
public String getState3() {
return state3;
}
public void setState3(String state3) {
this.state3 = state3;
}
// 创建备忘录
public Memento createMemento(){
// 将要被保存的数据保存到备忘录中
return new Memento(BeanUtils.backupProp(this));
}
// 从备忘录恢复
public void restoreMemento(Memento memento){
// 从备忘录中恢复被保存的数据
BeanUtils.restoreProp(this, memento.getStateMap());
}
public String toString(){
return "state1="+state1+"state2="+state2+"state3="+state3;
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 备忘录角色:保存所有需要备份的数据
class Memento {
// 保存多个属性值
private Map<String, Object> stateMap;
public Memento(Map<String, Object> map){
this.stateMap = map;
}
// 获得保存的数据
public Map<String, Object> getStateMap() {
return stateMap;
}
// 存储保存的数据
public void setStateMap(Map<String, Object> stateMap) {
this.stateMap = stateMap;
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 备份工具:将多个属性保存到 Map 中 或恢复
class BeanUtils {
// 保存内容到备忘录
public static Map<String, Object> backupProp(Object bean){
Map<String, Object> result = new HashMap<String, Object>();
try{
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor des: descriptors){
String fieldName = des.getName();
Method getter = des.getReadMethod();
Object fieldValue = getter.invoke(bean, new Object[]{});
if(!fieldName.equalsIgnoreCase("class")){
result.put(fieldName, fieldValue);
}
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
// 从备忘录恢复内容
public static void restoreProp(Object bean, Map<String, Object> propMap){
try {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor des: descriptors){
String fieldName = des.getName();
if(propMap.containsKey(fieldName)){
Method setter = des.getWriteMethod();
setter.invoke(bean, new Object[]{propMap.get(fieldName)});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 管理者角色:管理备忘录实例的
class Caretaker {
// 保存多个备忘录
private Map<String, Memento> memMap = new HashMap<String, Memento>();
// 获得备忘录
public Memento getMemento(String index){
return memMap.get(index);
}
// 保存备忘录
public void setMemento(String index, Memento memento){
this.memMap.put(index, memento);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 测试
class Client {
public static void main(String[] args){
// 初始化发起者状态
Originator ori = new Originator();
ori.setState1("中国");
ori.setState2("强盛");
ori.setState3("繁荣");
System.out.println("===初始化状态===\n"+ori);
// 创建管理者
Caretaker caretaker = new Caretaker();
caretaker.setMemento("001",ori.createMemento()); // 发起者创建备忘录保存到管理者中
// 更改发起者状态
ori.setState1("软件");
ori.setState2("架构");
ori.setState3("优秀");
System.out.println("===修改后状态===\n"+ori);
// 通过管理者恢复备份的数据
ori.restoreMemento(caretaker.getMemento("001"));
System.out.println("===恢复后状态===\n"+ori);
}
}
策略模式
///////////////////////////////////////////////////////////////////////////////////
// 抽象策略
interface IStrategy {
public void doSomething();
}
// 具体策略 1
class ConcreteStrategy1 implements IStrategy {
public void doSomething() {
System.out.println("具体策略1");
}
}
// 具体策略 2
class ConcreteStrategy2 implements IStrategy {
public void doSomething() {
System.out.println("具体策略2");
}
}
///////////////////////////////////////////////////////////////////////////////////////
// 封装类:也叫上下文,对策略进行二次封装,目的是避免高层模块对策略的直接调用
class Context {
// 指向具体的策略
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy = strategy;
}
public void execute(){
strategy.doSomething();
}
}
///////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args){
/* 使用策略类来调用封装类 */
Context context;
// 以具体策略 1 设置封装类
System.out.println("-----执行策略1-----");
context = new Context(new ConcreteStrategy1());
context.execute();
// 以具体策略 2 设置封装类
System.out.println("-----执行策略2-----");
context = new Context(new ConcreteStrategy2());
context.execute();
}
}
迭代器模式
// 定义:提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部细节。
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象迭代器:(Iterator)
定义遍历元素所需要的方法,一般来说会有这么三个方法:取得第一个元素的方法first(),取得下一个元素
的方法next(),判断是否遍历结束的方法isDone()(或者叫hasNext()),移出当前对象的方法remove(),*/
interface Iterator {
public Object next(); // 迭代到下一个
public boolean hasNext(); // 判断是否有下一个
}
/* 迭代器实现: (ConcreteIterator)
实现迭代器接口中定义的方法,完成集合的迭代。*/
class ConcreteIterator implements Iterator{
// 用来保存容器中数据
private List list = new ArrayList();
private int cursor = 0; // 游标
public ConcreteIterator(List list){
this.list = list;
}
public boolean hasNext() {
if(cursor==list.size()){
return false;
}
return true;
}
public Object next() {
Object obj = null;
if(this.hasNext()){
obj = this.list.get(cursor++);
}
return obj;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象容器: (Aggregate)
一般是一个接口,提供一个iterator()方法,例如java中的Collection接口,List接口,Set接口等。*/
interface Aggregate {
public void add(Object obj);
public void remove(Object obj);
// 依赖 关系
public Iterator iterator();
}
/* 具体容器:(ConcreteAggregate)
就是抽象容器的具体实现类,比如List接口的有序列表实现ArrayList,List接口的链表实现LinkList,Set
接口的哈希列表的实现HashSet等。*/
class ConcreteAggregate implements Aggregate {
// 容量里面的数据
private List list = new ArrayList();
public void add(Object obj) {
list.add(obj);
}
public void remove(Object obj) {
list.remove(obj);
}
// 将容量里面的数据传给迭代器
public Iterator iterator() {
// 这是具体的迭代器实例
return new ConcreteIterator(list);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 客户
public class Client {
public static void main(String[] args){
// 创建容器并添加数据
Aggregate ag = new ConcreteAggregate();
ag.add("小明");
ag.add("小红");
ag.add("小刚");
// 初始化一个迭代器,即将容器里面的数据传给迭代器了
Iterator it = ag.iterator();
// 迭代
while(it.hasNext()){
// 从迭代器获得数据
String str = (String)it.next(); // next 函数迭代的是游标 cursor++,即迭代器内部数据迭加
System.out.println(str);
}
}
}
访问者模式
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象访问者类: (Visitor)
抽象类或者接口,声明访问者可以访问哪些元素,具体到程序中就是visit方法中的参数定义哪些对象是可以被访问的。*/
interface IVisitor {
public void visit(ConcreteElement1 el1);
public void visit(ConcreteElement2 el2);
}
/* 具体访问者: (ConcreteVisitor)
实现抽象访问者所声明的方法,它影响到访问者访问到一个类后该干什么,要做什么事情。*/
class Visitor implements IVisitor {
// 调用具体元素 1 函数
public void visit(ConcreteElement1 el1) {
el1.doSomething();
}
// 调用具体元素 2 函数
public void visit(ConcreteElement2 el2) {
el2.doSomething();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象元素类: (Element)
接口或者抽象类,声明接受哪一类访问者访问,程序上是通过accept方法中的参数来定义的。抽象元素一
般有两类方法,一部分是本身的业务逻辑,另外就是允许接收哪类访问者来访问。*/
abstract class Element {
// 调用访问者类的 visit() 访问本元素的 doSomething(),即 accept() --> 访问者
public abstract void accept(IVisitor visitor);
// 元素类特定
public abstract void doSomething();
}
/* 具体元素类 1: (ConcreteElement)
实现抽象元素类所声明的accept方法,通常都是visitor.visit(this),基本上已经形成一种定式了 */
class ConcreteElement1 extends Element {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
public void doSomething(){
System.out.println("这是元素1");
}
}
/* 具体元素类 2: (ConcreteElement)
实现抽象元素类所声明的accept方法,通常都是visitor.visit(this),基本上已经形成一种定式了 */
class ConcreteElement2 extends Element {
public void accept(IVisitor visitor) {
visitor.visit(this);
}
public void doSomething(){
System.out.println("这是元素2");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 结构对象: (ObjectStruture)
一个元素的容器,一般包含一个容纳多个不同类、不同接口的容器,如 List、Set、Map 等,在项目中一般很少抽象出这个角色。*/
class ObjectStruture {
// 获得元素类链表
public static List<Element> getList(){
// 一个元素类链表
List<Element> list = new ArrayList<Element>();
// 随机往里面添加元素 1 或元素 2
Random ran = new Random();
for(int i=0; i<10; i++){
int a = ran.nextInt(100);
if(a>50){
list.add(new ConcreteElement1());
}else{
list.add(new ConcreteElement2());
}
}
return list;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// 调用类 (Client)
public class Client {
public static void main(String[] args){
// 一个元素类链表,通过 ObjectStruture.getList() 初始化
List<Element> list = ObjectStruture.getList();
// 遍历元素类链表
for(Element e: list){
e.accept(new Visitor()); // 经访问者调用元素类本身操作函数,调用流程:元素类.accept() --> 访问者类.visit() --> 元素类.doSomething()
}
}
}
观察者模式
Java API :
/* 简单例子:
购房者都关注着房子的价格变化,每当房子价格变化时,所有的购房者都
可以观察得到,实现上以上的购房者都属于观察者。
观察者模式实现:
在 java.util 包中提供了 Observable 类和 Observer 接口,使用它们即可完成
观察者模式。需要被观察的类必须继承 Observable 类,Observable 类的常用方法如
表 11-17 所示:
public void addObserver(Observer o) 添加一个观察者
public void deleteObserver(Observer o) 删除一个观察者
protected void setChanged() 被观察者状态发生改变
public void notifyObservers(Object o) 通知所有观察者状态改变
然后每一个观察者都需要实现 Observer 接口,Observer 接口定义如下:
public interface Observer{
void update(Observable o, Object arg);
} */
import java.util.* ;
// 被观察者
class House extends Observable{ // 表示房子可以被观察
private float price ; // 价钱
public House(float price){
this.price = price ;
}
public float getPrice(){
return this.price ;
}
public void setPrice(float price){
// 每一次修改的时候都应该引起观察者的注意
super.setChanged() ; // 设置变化点
super.notifyObservers(price) ; // 价格被改变
this.price = price ;
}
public String toString(){
return "房子价格为:" + this.price ;
}
};
// 观察者
class HousePriceObserver implements Observer{
private String name ;
public HousePriceObserver(String name){ // 设置每一个购房者的名字
this.name = name ;
}
// 被观察者变动时调用的函数
public void update(Observable o,Object arg){
if(arg instanceof Float){
System.out.print(this.name + "观察到价格更改为:") ;
System.out.println(((Float)arg).floatValue()) ;
}
}
};
// 测试
public class ObserDemo01{
public static void main(String args[]){
House h = new House(1000000) ;
HousePriceObserver hpo1 = new HousePriceObserver("购房者A") ;
HousePriceObserver hpo2 = new HousePriceObserver("购房者B") ;
HousePriceObserver hpo3 = new HousePriceObserver("购房者C") ;
h.addObserver(hpo1) ;
h.addObserver(hpo2) ;
h.addObserver(hpo3) ;
System.out.println(h) ; // 输出房子价格
h.setPrice(666666) ; // 修改房子价格
System.out.println(h) ; // 输出房子价格
}
};
自己实现:
//////////////////////////////////////////////////////////////////////////////
// 被观察者抽象角色
abstract class Subject {
// 被观察者列表
private Vector<Observer> obs = new Vector<Observer>();
public void addObserver(Observer obs){
this.obs.add(obs);
}
public void delObserver(Observer obs){
this.obs.remove(obs);
}
protected void notifyObserver(){
// 遍历观察者列表,调用其 update()
for(Observer o: obs){
o.update();
}
}
public abstract void doSomething();
}
// 具体被观察者角色
class ConcreteSubject extends Subject {
public void doSomething(){
System.out.println("被观察者事件反生");
this.notifyObserver();
}
}
//////////////////////////////////////////////////////////////////////////////
// 抽象观察者角色
interface Observer {
public void update();
}
// 具体观察者角色
class ConcreteObserver1 implements Observer {
public void update() {
System.out.println("观察者1收到信息,并进行处理。");
}
}
// 具体观察者角色
class ConcreteObserver2 implements Observer {
public void update() {
System.out.println("观察者2收到信息,并进行处理。");
}
}
//////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args){
Subject sub = new ConcreteSubject();
sub.addObserver(new ConcreteObserver1()); //添加观察者1
sub.addObserver(new ConcreteObserver2()); //添加观察者2
// 手动触发被观察事件
sub.doSomething();
}
}
/*
运行结果
被观察者事件反生
观察者1收到信息,并进行处理。
观察者2收到信息,并进行处理。
*/
解释器模式
/*
例:
R1 = 100
R2 = 200
R= R1 + R2
*/
//////////////////////////////////////////////////////////////////////////
//上下文(环境)角色,使用 HashMap 来存储变量对应的数值,如 R= R1+R2,R1,R2 的值就保存在这里
class Context{
//////////////////////////////////////
// 用来保存参与计算的变量的值
private Map valueMap = new HashMap();
public void addValue(Variable x , int y){
Integer yi = new Integer(y);
valueMap.put(x , yi);
}
public int LookupValue(Variable x){
int i = ((Integer)valueMap.get(x)).intValue();
return i ;
}
}
///////////////////////////////////////////////////////////////////////////
//抽象表达式角色,也可以用接口来实现
abstract class Expression{
// 统一的运算接口
public abstract int interpret(Context con);
}
///////////////////////////////////////////////////////////////////////////
//终结符表达式角色:常量
class Constant extends Expression{
/////////////////////////////
// 保存常量的值
private int i ;
public Constant(int i){
this.i = i;
}
public int interpret(Context con){
return i ;
}
}
//终结符表达式角色:变量
class Variable extends Expression{
public int interpret(Context con) {
//this 为调用 interpret 方法的 Variable 对象
return con.LookupValue(this);
}
}
/////////////////////////////////////////////////////////////////////////////
//非终结符表达式角色
// 加
class Add extends Expression{
// 指向左,右表达式
private Expression left ,right ;
public Add(Expression left , Expression right) {
this.left = left ;
this.right= right ;
}
public int interpret(Context con){
return left.interpret(con) + right.interpret(con);
}
}
// 减
class Subtract extends Expression{
// 指向左,右表达式
private Expression left , right ;
public Subtract(Expression left , Expression right) {
this.left = left ;
this.right= right ;
}
public int interpret(Context con){
return left.interpret(con) - right.interpret(con);
}
}
// 乘
class Multiply extends Expression{
// 指向左,右表达式
private Expression left , right ;
public Multiply(Expression left , Expression right){
this.left = left ;
this.right= right ;
}
public int interpret(Context con){
return left.interpret(con) * right.interpret(con);
}
}
// 除
class Division extends Expression{
// 指向左,右表达式
private Expression left , right ;
public Division(Expression left , Expression right){
this.left = left ;
this.right= right ;
}
public int interpret(Context con){
try{
return left.interpret(con) / right.interpret(con);
}catch(ArithmeticException ae) {
System.out.println("被除数为 0! ");
return -11111;
}
}
}
//////////////////////////////////////////////////////////////////////////////////
//测试程序,计算 (a*b)/(a-b+2)
public class Test
{
private static Expression ex ;
private static Context con ;
public static void main(String[] args){
// 上下文实例化
con = new Context();
//设置变量、常量
Variable a = new Variable();
Variable b = new Variable();
// 设置常量
Constant c = new Constant(2);
//为变量赋值
con.addValue(a , 5);
con.addValue(b , 7);
//运算【对句子的结构由我们自己来分析,构造,这里省事就不解析构造了,直接运算】
ex = new Division(new Multiply(a , b), new Add(new Subtract(a , b) , c));
System.out.println("运算结果为: "+ex.interpret(con));
}
}
命令模式
//////////////////////////////////////////////////////////////
// 命令接收者相关类:
//抽象接收者,定义了每个接收者应该完成的业务逻辑
abstract class AbstractReceiver {
public abstract void doJob();
}
// 具体接收者01,实现自己真正的业务逻辑
class Receiver01 extends AbstractReceiver {
public void doJob() {
System.out.println("接收者01 完成工作 ...\n");
}
}
// 具体接收者02,实现自己真正的业务逻辑
class Receiver02 extends AbstractReceiver {
public void doJob() {
System.out.println("接收者02 完成工作 ...\n");
}
}
//////////////////////////////////////////////////////////////
// 命令类:
// 抽象命令类,定义了每个具体命令被执行的入口方法execute()
abstract class AbstractCommand {
public abstract void execute();
}
// 具体命令类01,通过构造函数的参数决定了该命令由哪个接收者执行
class Command01 extends AbstsractCommand {
private AbstractReceiver receiver = null;
public Command01(AbstractReceiver receiver) {
this.receiver = receiver;
}
public void execute() {
System.out.println("命令01 被发布 ...");
this.receiver.doJob();
}
}
// 具体命令类02,通过构造函数的参数决定了该命令由哪个接收者执行
class Command02 extends AbstractCommand {
private AbstractReceiver receiver = null;
public Command02(AbstractReceiver receiver) {
this.receiver = receiver;
}
public void execute() {
System.out.println("命令02 被发布 ...");
this.receiver.doJob();
}
}
//////////////////////////////////////////////////////////
// 调用者类:
// 调用者,负责将具体的命令传送给具体的接收者
class Invoker {
private AbstractCommand command = null;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void action() {
this.command.execute();
}
}
///////////////////////////////////////////////////////////
// 测试类:
//测试类
public class Client {
public static void main(String[] args) {
// 创建调用者
Invoker invoker = new Invoker();
// 创建一个具体命令,并指定该命令被执行的具体接收者
AbstractCommand command01 = new Command01(new Receiver01());
// 给调用者发布一个具体命令
invoker.setCommand(command01);
// 调用者执行命令,其实是将其传送给具体的接收者并让其真正执行
invoker.action();
AbstractCommand command02 = new Command01(new Receiver02());
invoker.setCommand(command02);
invoker.action();
}
}
/*
测试结果:
命令01 被发布 ...
接收者01 完成工作 ...
命令02 被发布 ...
接收者02 完成工作 ...
如上面测试中输出的结果,我们知道在客户端中每次声明并创建一个具体的命令对象时总要显式地将
其指定给某一具体的接收者(也就是命令的最终执行者),这似乎不太灵活,在现实中有些命令的发布也
确实不是预先就指定了该命令的接收者的。
*/
////////////////////////////////////////////////////////////////
// 命令类:
/*
* 抽象命令类,使用构造函数的传入参数预先内定具体接收者, 若想使用其他接收者,可在子类的构造函数中传入
*/
abstract class AbstractCommand {
protected AbstractReceiver receiver = null;
public AbstractCommand(AbstractReceiver receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
// 具体命令类01,提供无参、有参两种构造函数
class Command01 extends AbstractCommand {
// 使用无参构造函数来默认使用的具体接收者
public Command01() {
super(new Receiver01());
}
// 使用有参构造函数来指定具体的接收者
public Command01(AbstractReceiver receiver) {
super(receiver);
}
public void execute() {
System.out.println("命令01 被发布 ...")
this.receiver.doJob();
}
}
// 具体命令类02,提供无参、有参两种构造函数
class Command02 extends AbstractCommand {
// 使用无参构造函数来默认使用的具体接收者
public Command02() {
super(new Receiver02());
}
// 使用有参构造函数来指定具体的接收者
public Command02(AbstractReceiver receiver) {
super(receiver);
}
public void execute() {
System.out.println("命令02 被发布 ...")
this.receiver.doJob();
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 修改后的测试类:
// 测试类
public class Client {
public static void main(String[] args) {
// 创建调用者
Invoker invoker = new Invoker();
// 创建一个具体命令,并指定该命令被执行的具体接收者
// AbstractCommand command01 = new Command01(new Receiver01());
AbstractCommand command01 = new Command01();
// 给调用者发布一个具体命令
invoker.setCommand(command01);
// 调用者执行命令,其实是将其传送给具体的接收者并让其真正执行
invoker.action();
// AbstractCommand command02 = new Command01(receiver02);
AbstractCommand command02 = new Command02();
invoker.setCommand(command02);
invoker.action();
System.out.println("\n设置命令01由接收者02执行...");
command01 = new Command01(new Receiver02());
invoker.setCommand(command01);
invoker.action();
}
}
/*
测试结果:
命令01 被发布 ...
接收者01 完成工作 ...
命令02 被发布 ...
接收者02 完成工作 ...
设置命令01由接收者02执行...
命令01 被发布 ...
接收者02 完成工作 ...
*/
通用类型:
// 客户端中每次声明并创建一个具体的命令对象时总要显式地将其指定给某一具体的接收者(也就是命令的最终执行者)
//////////////////////////////////////////////////////////////
// 命令接收者相关类:
//抽象接收者,定义了每个接收者应该完成的业务逻辑
abstract class AbstractReceiver {
public abstract void doJob();
}
// 具体接收者01,实现自己真正的业务逻辑
class Receiver01 extends AbstractReceiver {
public void doJob() {
System.out.println("接收者01 完成工作 ...\n");
}
}
// 具体接收者02,实现自己真正的业务逻辑
class Receiver02 extends AbstractReceiver {
public void doJob() {
System.out.println("接收者02 完成工作 ...\n");
}
}
//////////////////////////////////////////////////////////////
// 命令类:
// 抽象命令类,定义了每个具体命令被执行的入口方法execute()
abstract class AbstractCommand {
public abstract void execute();
}
// 具体命令类01,通过构造函数的参数决定了该命令由哪个接收者执行
class Command01 extends AbstsractCommand {
private AbstractReceiver receiver = null;
public Command01(AbstractReceiver receiver) {
this.receiver = receiver;
}
public void execute() {
System.out.println("命令01 被发布 ...");
this.receiver.doJob();
}
}
// 具体命令类02,通过构造函数的参数决定了该命令由哪个接收者执行
class Command02 extends AbstractCommand {
private AbstractReceiver receiver = null;
public Command02(AbstractReceiver receiver) {
this.receiver = receiver;
}
public void execute() {
System.out.println("命令02 被发布 ...");
this.receiver.doJob();
}
}
//////////////////////////////////////////////////////////
// 调用者类:
// 调用者,负责将具体的命令传送给具体的接收者
class Invoker {
// 指向要调用的命令
private AbstractCommand command = null;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void action() {
this.command.execute();
}
}
///////////////////////////////////////////////////////////
// 测试类:
// 测试类
public class Client {
public static void main(String[] args) {
// 创建调用者
Invoker invoker = new Invoker();
// 创建一个具体命令,并指定该命令被执行的具体接收者
AbstractCommand command01 = new Command01(new Receiver01()); // 【缺点:执行前就需要绑定命令类与执行者】
// 给调用者发布一个具体命令
invoker.setCommand(command01);
// 调用者执行命令,其实是将其传送给具体的接收者并让其真正执行
invoker.action();
AbstractCommand command02 = new Command01(new Receiver02());
invoker.setCommand(command02);
invoker.action();
}
}
/*
测试结果:
命令01 被发布 ...
接收者01 完成工作 ...
命令02 被发布 ...
接收者02 完成工作 ...
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
如上面测试中输出的结果,我们知道在客户端中每次声明并创建一个具体的命令对象时总要显式地将
其指定给某一具体的接收者(也就是命令的最终执行者),这似乎不太灵活,在现实中有些命令的发布也
确实不是预先就指定了该命令的接收者的。*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
修改类型:
// 不再需要客户端中每次声明并创建一个具体的命令对象时总要显式地将其指定给某一具体的接收者(也就是命令的最终执行者)
// 【而是在声明时直接绑定了】。
/////////////////////////////////////////////////////////////
// 命令接收者相关类:
//抽象接收者,定义了每个接收者应该完成的业务逻辑
abstract class AbstractReceiver {
public abstract void doJob();
}
// 具体接收者01,实现自己真正的业务逻辑
class Receiver01 extends AbstractReceiver {
public void doJob() {
System.out.println("接收者01 完成工作 ...\n");
}
}
// 具体接收者02,实现自己真正的业务逻辑
class Receiver02 extends AbstractReceiver {
public void doJob() {
System.out.println("接收者02 完成工作 ...\n");
}
}
//////////////////////////////////////////////////////////
// 调用者类:
// 调用者,负责将具体的命令传送给具体的接收者
class Invoker {
private AbstractCommand command = null;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void action() {
this.command.execute();
}
}
////////////////////////////////////////////////////////////////////////
// 修改后的命令类:
/*
* 抽象命令类,使用构造函数的传入参数预先内定具体接收者, 若想使用其他接收者,可在子类的构造函数中传入
*/
abstract class AbstractCommand {
// 在抽象类定义了一个默认的接收者,这样当有需要时再修改,否则直接继承
protected AbstractReceiver receiver = null;
public AbstractCommand(AbstractReceiver receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
// 具体命令类01,提供无参、有参两种构造函数
class Command01 extends AbstractCommand {
//////////////////////////////////////////////////
// 使用无参构造函数来默认使用的具体接收者
public Command01() {
super(new Receiver01());
}
///////////////////////////////////////////////////
// 使用有参构造函数来指定具体的接收者
public Command01(AbstractReceiver receiver) {
super(receiver);
}
public void execute() {
System.out.println("命令01 被发布 ...")
this.receiver.doJob();
}
}
// 具体命令类02,提供无参、有参两种构造函数
class Command02 extends AbstractCommand {
// 使用无参构造函数来默认使用的具体接收者
public Command02() {
super(new Receiver02());
}
// 使用有参构造函数来指定具体的接收者
public Command02(AbstractReceiver receiver) {
super(receiver);
}
public void execute() {
System.out.println("命令02 被发布 ...")
this.receiver.doJob();
}
}
//////////////////////////////////////////////////////////////////////////////////////
// 修改后的测试类:
// 测试类
public class Client {
public static void main(String[] args) {
// 创建调用者
Invoker invoker = new Invoker();
// 创建一个具体命令,并指定该命令被执行的具体接收者
// AbstractCommand command01 = new Command01(new Receiver01());
AbstractCommand command01 = new Command01(); // 使用无参命令时会自己创建一个默认接收者
// 给调用者发布一个具体命令
invoker.setCommand(command01);
// 调用者执行命令,其实是将其传送给具体的接收者并让其真正执行
invoker.action();
// AbstractCommand command02 = new Command01(receiver02);
AbstractCommand command02 = new Command02();
invoker.setCommand(command02);
invoker.action();
System.out.println("\n设置命令01由接收者02执行...");
command01 = new Command01(new Receiver02());
invoker.setCommand(command01);
invoker.action();
}
}
/*
测试结果:
命令01 被发布 ...
接收者01 完成工作 ...
命令02 被发布 ...
接收者02 完成工作 ...
设置命令01由接收者02执行...
命令01 被发布 ...
接收者02 完成工作 ...
*/
模板方法模式
////////////////////////////////////////////////////////////////////////////////////////
// 抽象类
abstract class AbstractSort {
/**
* 将数组array由小到大排序
* @param array
*/
protected abstract void sort(int[] array); // 父类定义好,子类去实现
public void showSortResult(int[] array){
this.sort(array);
System.out.print("排序结果:");
for (int i = 0; i < array.length; i++){
System.out.printf("%3s", array[i]);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////
// 实现类
class ConcreteSort extends AbstractSort {
@Override
protected void sort(int[] array){
for(int i=0; i<array.length-1; i++){
selectSort(array, i);
}
}
private void selectSort(int[] array, int index) {
int MinValue = 32767; // 最小值变量
int indexMin = 0; // 最小值索引变量
int Temp; // 暂存变量
for (int i = index; i < array.length; i++) {
if (array[i] < MinValue){ // 找到最小值
MinValue = array[i]; // 储存最小值
indexMin = i;
}
}
Temp = array[index]; // 交换两数值
array[index] = array[indexMin];
array[indexMin] = Temp;
}
}
////////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组
public static void main(String[] args){
AbstractSort s = new ConcreteSort();
s.showSortResult(a);
}
}
/* 运行结果:
排序结果: 0 1 3 4 5 7 9 10 12 32 */
责任链模式
// 任务优先级
class Level {
private int level = 0;
public Level(int level){
this.level = level;
};
public boolean above(Level level){
if(this.level >= level.level){
return true;
}
return false;
}
}
// 任请请求项
class Request {
Level level;
public Request(Level level){
this.level = level;
}
public Level getLevel(){
return level;
}
}
// 处理结构项
class Response {
}
/////////////////////////////////////////////////////////////////////////////////////////
// 抽象处理类
abstract class Handler {
//////////////////////////////////////////////////
// 这个类似一个对象链表,保存下一个对象
private Handler nextHandler;
/////////////////////////////////////////////////
// 调用责任链函数
public final Response handleRequest(Request request){
Response response = null;
// 判断当前对象的处理等级是否大于请求
if(this.getHandlerLevel().above(request.getLevel())){
// 用当前对象进行处理
response = this.response(request);
}else{
if(this.nextHandler != null){
this.nextHandler.handleRequest(request);
}else{
System.out.println("-----没有合适的处理器-----");
}
}
return response;
}
///////////////////////////////////////////////
// 设置责任链函数
public void setNextHandler(Handler handler){
this.nextHandler = handler;
}
///////////////////////////////////////////////
// 设置子类必须有的实现的函数
protected abstract Level getHandlerLevel();
public abstract Response response(Request request);
}
//////////////////////////////////////////////////////////////////////////////////////
// 具体处理类 1
class ConcreteHandler1 extends Handler {
protected Level getHandlerLevel() {
return new Level(1);
}
public Response response(Request request) {
System.out.println("-----请求由处理器1进行处理-----");
return null;
}
}
// 具体处理类 2
class ConcreteHandler2 extends Handler {
protected Level getHandlerLevel() {
return new Level(3);
}
public Response response(Request request) {
System.out.println("-----请求由处理器2进行处理-----");
return null;
}
}
// 具体处理类 3
class ConcreteHandler3 extends Handler {
protected Level getHandlerLevel() {
return new Level(5);
}
public Response response(Request request) {
System.out.println("-----请求由处理器3进行处理-----");
return null;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args){
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3();
// 组成责任链
handler1.setNextHandler(handler2);
handler2.setNextHandler(handler3);
// 调用责任链
Response response = handler1.handleRequest(new Request(new Level(4)));
}
}
中介者模式
// 在中介者模式中,同事类之间必须通过中介者才能进行消息传递
/////////////////////////////////////////////////////////////////////////////////
// 抽象同事
abstract class AbstractColleague {
protected int number;
public int getNumber() {
return number;
}
public void setNumber(int number){
this.number = number;
}
//注意这里的参数不再是同事类,而是一个中介者 ,通过中介者影响同事
public abstract void setNumber(int number, AbstractMediator am);
}
// 具体同事 A
class ColleagueA extends AbstractColleague{
public void setNumber(int number, AbstractMediator am) {
this.number = number;
am.AaffectB();
}
}
// 具体同事 B
class ColleagueB extends AbstractColleague{
@Override
public void setNumber(int number, AbstractMediator am) {
this.number = number;
am.BaffectA();
}
}
//////////////////////////////////////////////////////////////////////////////////
// 抽象中介者
abstract class AbstractMediator {
// 两个变量保存需要互相影响的具体同事类
protected AbstractColleague A;
protected AbstractColleague B;
public AbstractMediator(AbstractColleague a, AbstractColleague b) {
A = a;
B = b;
}
public abstract void AaffectB();
public abstract void BaffectA();
}
// 具体中介者
class Mediator extends AbstractMediator {
public Mediator(AbstractColleague a, AbstractColleague b) {
super(a, b);
}
//处理A对B的影响
public void AaffectB() {
int number = A.getNumber();
B.setNumber(number*100);
}
//处理B对A的影响
public void BaffectA() {
int number = B.getNumber();
A.setNumber(number/100);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args){
// 创建同事 A,同事 B
AbstractColleague collA = new ColleagueA();
AbstractColleague collB = new ColleagueB();
// 设置一个中介
AbstractMediator am = new Mediator(collA, collB);
// 同事通过中介互相影响
System.out.println("==========通过设置A影响B==========");
collA.setNumber(1000, am);
System.out.println("collA的number值为:"+collA.getNumber());
System.out.println("collB的number值为A的10倍:"+collB.getNumber());
System.out.println("==========通过设置B影响A==========");
collB.setNumber(1000, am);
System.out.println("collB的number值为:"+collB.getNumber());
System.out.println("collA的number值为B的0.1倍:"+collA.getNumber());
}
}
状态模式
//////////////////////////////////////////////////////////////////////////////////
/// Context类,维护一个ConcreteState子类的实例,这个实例定义当前的状态。
public class Context
{
// 表示当前状态
private State state;
/// 定义Context的初始状态
/// <param name="state"></param>
public Context(State state)
{
this.state = state;
}
/// 可读写的状态属性,用于读取和设置新状态
public State State
{
get { return state; }
set { state = value; }
}
/// 对请求做处理,并设置下一个状态
public void Request()
{
state.Handle(this);
}
}
/////////////////////////////////////////////////////////////////////////////////////
/// 抽象状态类,定义一个接口以封装与Context的一个特定状态相关的行为
public abstract class State
{
public abstract void Handle(Context context);
}
/// 具体状态类 A, 每一个子类实现一个与Context的一个状态相关的行为
public class ConcreteStateA : State
{
/// 设置ConcreteStateA的下一个状态是ConcreteStateB
/// <param name="context"></param>
public override void Handle(Context context)
{
Console.WriteLine("当前状态是 A.");
context.State = new ConcreteStateB();
}
}
/// 具体状态类 B
public class ConcreteStateB : State
{
/// 设置ConcreteStateB的下一个状态是ConcreteSateA
/// <param name="context"></param>
public override void Handle(Context context)
{
Console.WriteLine("当前状态是 B.");
// 改变上下文当前状态
context.State = new ConcreteStateA();
}
}
/////////////////////////////////////////////////////////////////////////////////////
// 测试
class Program
{
static void Main(string[] args)
{
// 设置Context的初始状态为ConcreteStateA
Context context = new Context(new ConcreteStateA());
// 不断地进行请求,同时更改状态
context.Request();
context.Request();
context.Request();
context.Request();
Console.Read();
}
}
行为型
代理模式
//////////////////////////////////////////////////////////
// 目标接口: 代理角色与具体角色共通
interface Network{
public void browse() ; // 浏览
}
////////////////////////////////////////////////////////////
// 真实角色
class Real implements Network{
public void browse(){
System.out.println("上网浏览信息") ;
}
};
////////////////////////////////////////////////////////////////
// 代理角色
class Proxy implements Network{
////////////////////////////////////////
// 这里指向直实角色, 通过在函数中调用真实角色函数,实现代理
private Network network ; // 代理对象
public Proxy(Network network){
this.network = network ;
}
public void check(){
System.out.println("检查用户是否合法。") ;
}
public void browse(){
this.check() ;
this.network.browse() ; // 调用真实的主题操作
}
};
//////////////////////////////////////////////////////////////////
// 测试
public class ProxyDemo{
public static void main(String args[]){
Network net = null ;
net = new Proxy(new Real()) ;// 指定代理操作
net.browse() ; // 客户只关心上网浏览一个操作
}
};
桥接模式
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 抽象化角色 (Abstraction)
* 它主要的职责是定义出该角色的行为,同时保存一个对实现化角色的引用,该角色一般是抽象类。
* @author Administrator
*
*/
public abstract class Abstraction {
//////////////////////////////////////////////////////
// 定义对实现化角色的引用
private Implementor imp;
// 约束子类必须实现该构造函数
public Abstraction(Implementor _imp) {
this.imp = _imp;
}
// 自身的行为和属性
public void request() {
this.imp.doSomething();
}
// 获得实现化角色
public Implementor getImp() {
return this.imp;
}
}
/**
* 具体抽象化角色 (RefinedAbstraction)
* 它引用实现化角色对抽象化角色进行修正。
* @author Administrator
*
*/
public class RefinedAbstraction extends Abstraction {
// 覆写构造函数
public RefinedAbstraction(Implementor _imp) {
// 将具体的实现实例保存在父类中
super(_imp);
}
/////////////////////////////////////////
// 修正父类的行为
@Override
public void request() {
/*
* 业务处理
*/
super.request();
// 这里可以调用实现化角色的对象
super.getImp().doAnything();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
/**
* 实现化角色 (Implementor)
* 它是接口或者抽象类,定义角色必须的行为和属性。
* @author Administrator
*
*/
public interface Implementor {
// 基本方法
public void doSomething();
public void doAnything();
}
/**
* 具体实现化角色 1 (ConcreteImplementor1)
* 它实现接口或抽象类定义的方法和属性。
* @author Administrator
*
*/
public class ConcreteImplementor1 implements Implementor {
public void doAnything() {
// 业务处理逻辑
}
public void doSomething() {
// 业务处理逻辑
}
}
/**
* 具体实现化角色 2 (ConcreteImplementor2)
* 它实现接口或抽象类定义的方法和属性。
* @author Administrator
*
*/
public class ConcreteImplementor2 implements Implementor {
public void doAnything() {
// 业务处理逻辑
}
public void doSomething() {
// 业务处理逻辑
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// 测试
public class Client {
public static void main(String[] args) {
// 定义一个实现化角色
Implementor imp = new ConcreteImplementor1();
// 定义一个抽象化角色, 并通过 RefinedAbstraction() 将实现化角色实例保存到父类中
Abstraction abs = new RefinedAbstraction(imp);
// 执行 RefinedAbstraction 类函数,通过上面的实现化角色实例,修正父类对应函数
abs.request();
}
}
适配器模式
类适配:
////////////////////////////////////////////////////////////////////////////////
// 被适配角色
// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
class Adaptee {
public void specificRequest() {
System.out.println("被适配类具有 特殊功能...");
}
}
//////////////////////////////////////////////////////////////////////////////
// 抽象目村要求接口
// 目标接口,或称为标准接口
interface Target {
public void request();
}
// 具体目标类,只提供普通功能
class ConcreteTarget implements Target {
public void request() {
System.out.println("普通类 具有 普通功能...");
}
}
///////////////////////////////////////////////////////////////////////////////
// 适配器类,继承了被适配类,同时实现标准接口
class Adapter extends Adaptee implements Target{
// extends:继承的是被适配角色
// implements: 继承的是要适配的接口
// 实现目标要求的接口,并在接口内调用被适配角色函数,实现适配
public void request() {
// 调用被适配器类的函数,实现适配
super.specificRequest();
}
}
///////////////////////////////////////////////////////////////////////////////
// 测试类public class Client {
public static void main(String[] args) {
// 使用普通功能类
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
// 使用特殊功能类,即适配类
Target adapter = new Adapter();
adapter.request();
}
}
对象适配:
////////////////////////////////////////////////////////////////////////////////
// 被适配角色
// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
class Adaptee {
public void specificRequest() {
System.out.println("被适配类具有 特殊功能...");
}
}
//////////////////////////////////////////////////////////////////////////////
// 抽象目村要求接口
// 目标接口,或称为标准接口
interface Target {
public void request();
}
// 具体目标类,只提供普通功能
class ConcreteTarget implements Target {
public void request() {
System.out.println("普通类 具有 普通功能...");
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// 适配器类,直接关联被适配类,同时实现标准接口
class Adapter implements Target{
// 直接关联被适配类
private Adaptee adaptee;
// 可以通过构造函数传入具体需要适配的被适配类对象
public Adapter (Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
// 这里是使用委托的方式完成特殊功能
this.adaptee.specificRequest();
}
}
////////////////////////////////////////////////////////////////////////////////////////
// 测试类
public class Client {
public static void main(String[] args) {
// 使用普通功能类
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
// 使用特殊功能类,即适配类,
// 需要先创建一个被适配类的对象作为参数
Target adapter = new Adapter(new Adaptee());
adapter.request();
}
}
外观模式
外观模式1:
package com.yeepay.sxf.template18;
//////////////////////////////////////////////////////////////////////////////////////////////
/** 【1】写信的业务类
* 写信的业务类
* 隐藏在门面角色里边,不需要暴露太多
* @author sxf
*
*/
public interface ILetterProcess {
//写信的内容
public void writeContext(String context);
//写信的地址
public void fillEnvelope(String address);
//将信装入信封
public void letterInotoEnvelope();
//发送信件
public void sendLetter();
}
// 【2】写信的业务类的实现
public class LetterProcessImpl implements ILetterProcess{
@Override
public void writeContext(String context) {
System.out.println("LetterProcessImpl.writeContext()写信的内容:"+context);
}
@Override
public void fillEnvelope(String address) {
// TODO Auto-generated method stub
System.out.println("LetterProcessImpl.fillEnvelope()写信的邮寄地址:"+address);
}
@Override
public void letterInotoEnvelope() {
System.out.println("LetterProcessImpl.letterInotoEnvelope()将信装入信封");
}
@Override
public void sendLetter() {
System.out.println("LetterProcessImpl.sendLetter()邮寄信");
}
}
/////////////////////////////////////////////////////////////////////////////////////////
/** 【3】写信的业务类的门面角色
* 写信的门面角色
* 一个人想写信,只需要给这个门面提供相应的参数,后续事件不用关心。
* @author sxf
*
*/
public class ModenPostOffce {
private ILetterProcess letterProcess;
public ModenPostOffce(ILetterProcess letterProcess){
this.letterProcess=letterProcess;
}
public void sendLetter(String context,String address){
//写信
letterProcess.writeContext(context);
//写地址
letterProcess.fillEnvelope(address);
//装信封
letterProcess.letterInotoEnvelope();
//发送信件
letterProcess.sendLetter();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
/** 【4】客户端测试
* 客户端测试
* @author sxf
*
*/
public class ClientTest {
public static void main(String[] args) {
//写信的业务类
ILetterProcess letterProcess=new LetterProcessImpl();
//写信业务类的门面类
ModenPostOffce modenPostOffce=new ModenPostOffce(letterProcess);
//一个人员通过门面写信
modenPostOffce.sendLetter("dddsdfdf", "cccccccccc");
}
}
外观模式 2:
using System;
//////////////////////////////////////////////////////////////////////////////////
/* 外观模式就是动里不动外,让外层好调用。*/
public class Camera
{
public void TurnOn()
{
Console.WriteLine("Turning on the camera.");
}
public void TurnOff()
{
Console.WriteLine("Turning off the camera.");
}
public void Rotate(int degrees)
{
Console.WriteLine("Rotating the camera by {0} degrees.", degrees);
}
}
public class Light
{
public void TurnOff()
{
Console.WriteLine("Turning on the light.");
}
public void TurnOn()
{
Console.WriteLine("Turning off the light.");
}
public void ChangeBulb()
{
Console.WriteLine("changing the light-bulb.");
}
}
public class Sensor
{
public void Activate()
{
Console.WriteLine("Activating the sensor.");
}
public void Deactivate()
{
Console.WriteLine("Deactivating the sensor.");
}
public void Trigger()
{
Console.WriteLine("The sensor has triggered.");
}
}
public class Alarm
{
public void Activate()
{
Console.WriteLine("Activating the alarm.");
}
public void Deactivate()
{
Console.WriteLine("Deactivating the alarm.");
}
public void Ring()
{
Console.WriteLine("Ringing the alarm.");
}
public void StopRing()
{
Console.WriteLine("Stop the alarm.");
}
}
//////////////////////////////////////////////////////////////////////////////////
/* 外观类 */
public class SecurityFacade
{
private static Camera camera1, camera2;
private static Light light1, light2, light3;
private static Sensor sensor;
private static Alarm alarm;
static SecurityFacade()
{
camera1 = new Camera();
camera2 = new Camera();
light1 = new Light();
light2 = new Light();
light3 = new Light();
sensor = new Sensor();
alarm = new Alarm();
}
public void Activate()
{
camera1.TurnOn();
camera2.TurnOn();
light1.TurnOn();
light2.TurnOn();
light3.TurnOn();
sensor.Activate();
alarm.Activate();
}
public void Deactivate()
{
camera1.TurnOff();
camera2.TurnOff();
light1.TurnOff();
light2.TurnOff();
light3.TurnOff();
sensor.Deactivate();
alarm.Deactivate();
}
}
//////////////////////////////////////////////////////////////////////////////////
/* 客户端 */
public class Client
{
private static SecurityFacade security;
public static void Main( string[] args )
{
security = new SecurityFacade();
security.Activate();
Console.WriteLine("\n--------------------\n");
security.Deactivate();
}
}
享元模式
享元模式 1:
package Flyweight;
/////////////////////////////////////////////////////////////////////////
// 抽象享元角色
public abstract class Flyweight{
public abstract void operation();
}
////////////////////////////////////////////////////////////////////////////
// 具体享元类
public class ConcreteFlyweight extends Flyweight{
private String string;
public ConcreteFlyweight(String str){
string = str;
}
public void operation()
{
System.out.println("Concrete---Flyweight : " + string);
}
}
///////////////////////////////////////////////////////////////////////////////
// 享元工厂角色
public class FlyweightFactory{
/////////////////////////////////////////////////////
// hash 表,实现核心,每次通过工厂产生新实例都会保存在这里
// 创建新实例之前会在这里查找
private Hashtable flyweights = new Hashtable();//----------------------------1
public FlyweightFactory(){}
public Flyweight getFlyWeight(Object obj){
Flyweight flyweight = (Flyweight) flyweights.get(obj);//----------------2
if(flyweight == null){//---------------------------------------------------3
//产生新的ConcreteFlyweight
flyweight = new ConcreteFlyweight((String)obj);
flyweights.put(obj, flyweight);//--------------------------------------5
}
return flyweight;//---------------------------------------------------------6
}
public int getFlyweightSize(){
return flyweights.size();
}
}
/////////////////////////////////////////////////////////////////////////////////
// 调用
public class FlyweightPattern{
FlyweightFactory factory = new FlyweightFactory();
Flyweight fly1;
Flyweight fly2;
Flyweight fly3;
Flyweight fly4;
Flyweight fly5;
Flyweight fly6;
/** *//** Creates a new instance of FlyweightPattern */
public FlyweightPattern(){
fly1 = factory.getFlyWeight("Google");
fly2 = factory.getFlyWeight("Qutr");
fly3 = factory.getFlyWeight("Google");
fly4 = factory.getFlyWeight("Google");
fly5 = factory.getFlyWeight("Google");
fly6 = factory.getFlyWeight("Google");
}
public void showFlyweight(){
fly1.operation();
fly2.operation();
fly3.operation();
fly4.operation();
fly5.operation();
fly6.operation();
int objSize = factory.getFlyweightSize();
System.out.println("objSize = " + objSize);
}
public static void main(String[] args){
System.out.println("The FlyWeight Pattern!");
FlyweightPattern fp = new FlyweightPattern();
fp.showFlyweight();
}
}
/*
Concrete---Flyweight : Google
Concrete---Flyweight : Qutr
Concrete---Flyweight : Google
Concrete---Flyweight : Google
Concrete---Flyweight : Google
Concrete---Flyweight : Google
objSize = 2
*/
单纯享元:
/////////////////////////////////////////////////////////////////////////////////////////////////
// 抽象享元(Flyweight)角色
public interface Flyweight {
//一个示意性方法,参数state是外蕴状态
public void operation(String state);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// 具体享元(ConcreteFlyweight)角色
public class ConcreteFlyweight implements Flyweight {
private Character intrinsicState = null;
/**
* 构造函数,内蕴状态作为参数传入
* @param state
*/
public ConcreteFlyweight(Character state){
this.intrinsicState = state;
}
/**
* 外蕴状态作为参数传入方法中,改变方法的行为,
* 但是并不改变对象的内蕴状态。
*/
@Override
public void operation(String state) {
// TODO Auto-generated method stub
System.out.println("Intrinsic State = " + this.intrinsicState);
System.out.println("Extrinsic State = " + state);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// 享元工厂(FlyweightFactory)角色
public class FlyweightFactory {
/////////////////////////////////////////////////////////////////////////////
// 通过这个 Hash 来保证复用的, 每次创建会在这里查找
private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>();
public Flyweight factory(Character state){
//先从缓存中查找对象
Flyweight fly = files.get(state);
if(fly == null){
//如果对象不存在则创建一个新的Flyweight对象
fly = new ConcreteFlyweight(state);
//把这个新的Flyweight对象添加到缓存中
files.put(state, fly);
}
return fly;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// 客户端角色
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
FlyweightFactory factory = new FlyweightFactory();
Flyweight fly = factory.factory(new Character('a'));
fly.operation("First Call");
fly = factory.factory(new Character('b'));
fly.operation("Second Call");
fly = factory.factory(new Character('a'));
fly.operation("Third Call");
}
}
复合享元:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 抽象享元角色类
public interface Flyweight {
//一个示意性方法,参数state是外蕴状态
public void operation(String state);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// 具体享元角色类
public class ConcreteFlyweight implements Flyweight {
////////////////////////////////////////////
private Character intrinsicState = null;
/**
* 构造函数,内蕴状态作为参数传入
* @param state
*/
public ConcreteFlyweight(Character state){
this.intrinsicState = state;
}
/**
* 外蕴状态作为参数传入方法中,改变方法的行为,
* 但是并不改变对象的内蕴状态。
*/
@Override
public void operation(String state) {
// TODO Auto-generated method stub
System.out.println("Intrinsic State = " + this.intrinsicState);
System.out.println("Extrinsic State = " + state);
}
}
/* 具体复合享元角色
复合享元对象是由单纯享元对象通过复合而成的,因此它提供了add()这样的聚集管理方法。由于一个复合享元对象具有不同的聚集
元素,这些聚集元素在复合享元对象被创建之后加入,这本身就意味着复合享元对象的状态是会改变的,因此复合享元对象是不能共享的。
复合享元角色实现了抽象享元角色所规定的接口,也就是operation()方法,这个方法有一个参数,代表复合享元对象的外蕴状态。一个
复合享元对象的所有单纯享元对象元素的外蕴状态都是与复合享元对象的外蕴状态相等的;而一个复合享元对象所含有的单纯享元对象的内蕴状态
一般是不相等的,不然就没有使用价值了。*/
public class ConcreteCompositeFlyweight implements Flyweight {
///////////////////////////////////////////////////////////////
// 保存复合享元数据,即多个数据
private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>();
/**
* 增加一个新的单纯享元对象到聚集中
*/
public void add(Character key , Flyweight fly){
files.put(key,fly);
}
/**
* 外蕴状态作为参数传入到方法中
*/
@Override
public void operation(String state) {
Flyweight fly = null;
for(Object o : files.keySet()){
fly = files.get(o);
fly.operation(state);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 享元工厂角色提供两种不同的方法,一种用于提供单纯享元对象,另一种用于提供复合享元对象。
public class FlyweightFactory {
private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>();
/**
* 复合享元工厂方法
*/
public Flyweight factory(List<Character> compositeState){
ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
for(Character state : compositeState){
compositeFly.add(state,this.factory(state));
}
return compositeFly;
}
/**
* 单纯享元工厂方法
*/
public Flyweight factory(Character state){
//先从缓存中查找对象
Flyweight fly = files.get(state);
if(fly == null){
//如果对象不存在则创建一个新的Flyweight对象
fly = new ConcreteFlyweight(state);
//把这个新的Flyweight对象添加到缓存中
files.put(state, fly);
}
return fly;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
// 客户端角色
public class Client {
public static void main(String[] args) {
// 创建一个数组
List<Character> compositeState = new ArrayList<Character>();
compositeState.add('a');
compositeState.add('b');
compositeState.add('c');
compositeState.add('a');
compositeState.add('b');
// 复合享元测试
FlyweightFactory flyFactory = new FlyweightFactory();
Flyweight compositeFly1 = flyFactory.factory(compositeState);
Flyweight compositeFly2 = flyFactory.factory(compositeState);
compositeFly1.operation("Composite Call");
System.out.println("---------------------------------");
System.out.println("复合享元模式是否可以共享对象:" + (compositeFly1 == compositeFly2));
// 单纯享元测试
Character state = 'a';
Flyweight fly1 = flyFactory.factory(state);
Flyweight fly2 = flyFactory.factory(state);
System.out.println("单纯享元模式是否可以共享对象:" + (fly1 == fly2));
}
}
装饰器模式
装饰器模式1:
///////////////////////////////////////////////////////////////////////////////////////////
//定义抽象被装饰者: Component
public interface Human {
public void wearClothes();
public void walkToWhere();
}
//////////////////////////////////////////////////////////////////////////////////////////////
//定义具体被装饰者: ConcreteComponent 被装饰者初始状态有些自己的装饰
public class Person implements Human {
@Override
public void wearClothes() {
// TODO Auto-generated method stub
System.out.println("穿什么呢。。");
}
@Override
public void walkToWhere() {
// TODO Auto-generated method stub
System.out.println("去哪里呢。。");
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
//定义抽象装饰者: Decorator
public abstract class Decorator implements Human {
private Human human;
public Decorator(Human human) {
this.human = human;
}
public void wearClothes() {
human.wearClothes();
}
public void walkToWhere() {
human.walkToWhere();
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//下面定义三种具体装饰: ConcreteDecorator 这是第一个,第二个第三个功能依次细化,即装饰者的功能越来越多
public class Decorator_zero extends Decorator {
public Decorator_zero(Human human) {
super(human);
}
public void goHome() {
System.out.println("进房子。。");
}
public void findMap() {
System.out.println("书房找找Map。。");
}
@Override
public void wearClothes() {
// TODO Auto-generated method stub
super.wearClothes();
goHome();
}
@Override
public void walkToWhere() {
// TODO Auto-generated method stub
super.walkToWhere();
findMap();
}
}
// 具体装饰: Decorator_first
public class Decorator_first extends Decorator {
public Decorator_first(Human human) {
super(human);
}
public void goClothespress() {
System.out.println("去衣柜找找看。。");
}
public void findPlaceOnMap() {
System.out.println("在Map上找找。。");
}
@Override
public void wearClothes() {
// TODO Auto-generated method stub
super.wearClothes();
goClothespress();
}
@Override
public void walkToWhere() {
// TODO Auto-generated method stub
super.walkToWhere();
findPlaceOnMap();
}
}
// 具体装饰: Decorator_two
public class Decorator_two extends Decorator {
public Decorator_two(Human human) {
super(human);
}
public void findClothes() {
System.out.println("找到一件D&G。。");
}
public void findTheTarget() {
System.out.println("在Map上找到神秘花园和城堡。。");
}
@Override
public void wearClothes() {
// TODO Auto-generated method stub
super.wearClothes();
findClothes();
}
@Override
public void walkToWhere() {
// TODO Auto-generated method stub
super.walkToWhere();
findTheTarget();
}
}
///////////////////////////////////////////////////////////////////////////////////////////
//测试类
public class Test {
public static void main(String[] args) {
// 声明一个被装饰者
Human person = new Person();
// 声明一个装饰:通过具体的装饰来打扮被装饰者,这里是一个 Decorator_two 对象
Decorator decorator = new Decorator_two(new Decorator_first(new Decorator_zero(person)));
// 基类指针指向 Decorator_two(), 调用流程为:Decorator_two.wearClothes() --> Decorator_first.wearClothes() --> Decorator_zero.wearClothes()
decorator.wearClothes();
decorator.walkToWhere();
}
}
装饰器模式 2:
/* 现在需要一个汉堡,主体是鸡腿堡,可以选择添加生菜、酱、辣椒等等许多其他的配料,这种情况下就可以使用装饰者模式。*/
package decorator;
/////////////////////////////////////////////////////////////////////////////////////////////
// 汉堡基类(被装饰者,相当于上面的(Component 抽象构件角色)
public abstract class Humburger {
protected String name ;
public String getName(){
return name;
}
public abstract double getPrice();
}
//////////////////////////////////////////////////////////////////////////////////////////////
// 鸡腿堡类(被装饰者的初始状态,有些自己的简单装饰,相当于上面的(ConcreteComponent 具体构件角色)
public class ChickenBurger extends Humburger {
public ChickenBurger(){
name = "鸡腿堡";
}
@Override
public double getPrice() {
return 10;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// 配料的基类(装饰者,用来对汉堡进行多层装饰,每层装饰增加一些配料,相当于上面(Decorator 装饰角色)
public abstract class Condiment extends Humburger {
public abstract String getName();
}
//////////////////////////////////////////////////////////////////////////////////////////////
// 生菜(装饰者的第一层,相当于上面的(ConcreteDecoratorA 具体装饰角色A)
public class Lettuce extends Condiment {
Humburger humburger;
public Lettuce(Humburger humburger){
this.humburger = humburger;
}
@Override
public String getName() {
return humburger.getName()+" 加生菜";
}
@Override
public double getPrice() {
return humburger.getPrice()+1.5;
}
}
// 辣椒(装饰者的第二层,相当于上面的(ConcreteDecoratorB 具体装饰角色B)
public class Chilli extends Condiment {
Humburger humburger;
public Chilli(Humburger humburger){
this.humburger = humburger;
}
@Override
public String getName() {
return humburger.getName()+" 加辣椒";
}
@Override
public double getPrice() {
return humburger.getPrice(); //辣椒是免费的哦
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// 测试类
public class Test {
public static void main(String[] args) {
// 获得一个被装饰类:鸡腿堡
Humburger humburger = new ChickenBurger();
System.out.println(humburger.getName()+" 价钱:"+humburger.getPrice());
// 通过【鸡腿堡】初始化生菜
Lettuce lettuce = new Lettuce(humburger);
System.out.println(lettuce.getName()+" 价钱:"+lettuce.getPrice());
// 通过【鸡腿堡】初始化辣椒
Chilli chilli = new Chilli(humburger);
System.out.println(chilli.getName()+" 价钱:"+chilli.getPrice());
// 通过【鸡腿堡+生菜】初始化辣椒
Chilli chilli2 = new Chilli(lettuce);
System.out.println(chilli2.getName()+" 价钱:"+chilli2.getPrice());
}
}
/*
输出:
鸡腿堡 价钱:10.0
鸡腿堡 加生菜 价钱:11.5
鸡腿堡 加辣椒 价钱:10.0
鸡腿堡 加生菜 加辣椒 价钱:11.5
*/
组合模式
组合模式 1:
//////////////////////////////////////////////////////////////////////////
/// 店面类 抽象出来的店面部件
// component 组件
public abstract class Storefront
{
//店名
protected string storeName = string.Empty;
public string StoreName
{
get
{
return storeName;
}
}
//添加店面
public abstract void Add(Storefront store);
//删除店面
public abstract void Remove(Storefront store);
//定义所有部件公用的行为 刷卡行为
public abstract void PayByCard();
}
///////////////////////////////////////////////////////////////////////////////////
// composite 组件:直营店
public class StoreOrBranch : Storefront
{
// 链表,用来保存 composite 组件 或 leaf 组件
List<Storefront> myStoreList = new List<Storefront>();
//构造函数
public StoreOrBranch() { }
public StoreOrBranch(string storeName)
{
this.storeName = storeName;
}
//刷卡消费
public override void PayByCard()
{
Console.WriteLine("店面{0}的积分已累加进该会员卡", storeName);
foreach (Storefront sf in myStoreList)
{
sf.PayByCard();
}
}
//增加店面
public override void Add(Storefront store)
{
myStoreList.Add(store);
}
//解除店面
public override void Remove(Storefront store)
{
myStoreList.Remove(store);
}
}
///////////////////////////////////////////////////////////////////////////////////////
// leaf 组件:加盟店
public class JoinInStore : Storefront
{
//构造函数
public JoinInStore() { }
public JoinInStore(string storeName)
{
this.storeName = storeName;
}
//刷卡消费
public override void PayByCard()
{
Console.WriteLine("店面{0}的积分已累加进该会员卡", storeName);
}
public override void Add(Storefront store)
{
throw new NotImplementedException();
}
public override void Remove(Storefront store)
{
throw new NotImplementedException();
}
}
/////////////////////////////////////////////////////////////////////////////////
static void Main(string[] args)
{
// 直营店有自己的链表,可以保存下面的加盟店或直营店
StoreOrBranch store = new StoreOrBranch("朝阳总店");
StoreOrBranch brach = new StoreOrBranch("东城分店");
JoinInStore jstore = new JoinInStore("海淀加盟店一");
JoinInStore jstore1 = new JoinInStore("上地加盟店二");
/* 树形结构:
朝阳总店
东城分店
海淀加盟店一 上地加盟店二
*/
brach.Add(jstore);
brach.Add(jstore1);
store.Add(brach);
store.PayByCard();
}
组合模式 2:
package design.composite;
//////////////////////////////////////////////////////////////////////////////////////////
// component 抽象构件角色
public abstract class Company {
private String name;
public Company(String name) {
this.name = name;
}
public Company() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected abstract void add(Company company);
protected abstract void romove(Company company);
protected abstract void display(int depth);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// composite 组件 1
public class ConcreteCompany extends Company {
private List<Company> cList;
public ConcreteCompany() {
cList = new ArrayList<Company>();
}
public ConcreteCompany(String name) {
super(name);
cList = new ArrayList<Company>() ;
}
@Override
protected void add(Company company) {
cList.add(company);
}
@Override
protected void display(int depth) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < depth; i++) {
sb.append("-");
}
System.out.println(new String(sb) + this.getName());
for (Company c : cList) {
c.display(depth + 2);
}
}
@Override
protected void romove(Company company) {
cList.remove(company);
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// leaf 组件 1
public class FinanceDepartment extends Company {
public FinanceDepartment(){
}
public FinanceDepartment(String name){
super(name);
}
@Override
protected void add(Company company) {
}
@Override
protected void display(int depth) {
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < depth; i++) {
sb.append("-");
}
System.out.println(new String(sb) + this.getName() ) ;
}
@Override
protected void romove(Company company) {
}
}
// leaf 组件 2
public class HRDepartment extends Company {
public HRDepartment(){
}
public HRDepartment(String name){
super(name);
}
@Override
protected void add(Company company) {
}
@Override
protected void display(int depth) {
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < depth; i++) {
sb.append("-");
}
System.out.println(new String(sb) + this.getName() ) ;
}
@Override
protected void romove(Company company) {
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
package design.composite;
/* 测试,最终形成了一种树形结构
总公司
/ | \
各个 ... 分公司
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Company root = new ConcreteCompany();
root.setName("北京总公司");
root.add(new HRDepartment("总公司人力资源部"));
root.add(new FinanceDepartment("总公司财务部"));
Company shandongCom = new ConcreteCompany("山东分公司");
shandongCom.add(new HRDepartment("山东分公司人力资源部"));
shandongCom.add(new FinanceDepartment("山东分公司账务部"));
Company zaozhuangCom = new ConcreteCompany("枣庄办事处");
zaozhuangCom.add(new FinanceDepartment("枣庄办事处财务部"));
zaozhuangCom.add(new HRDepartment("枣庄办事处人力资源部"));
Company jinanCom = new ConcreteCompany("济南办事处");
jinanCom.add(new FinanceDepartment("济南办事处财务部"));
jinanCom.add(new HRDepartment("济南办事处人力资源部"));
shandongCom.add(jinanCom);
shandongCom.add(zaozhuangCom);
Company huadongCom = new ConcreteCompany("上海华东分公司");
huadongCom.add(new HRDepartment("上海华东分公司人力资源部"));
huadongCom.add(new FinanceDepartment("上海华东分公司账务部"));
Company hangzhouCom = new ConcreteCompany("杭州办事处");
hangzhouCom.add(new FinanceDepartment("杭州办事处财务部"));
hangzhouCom.add(new HRDepartment("杭州办事处人力资源部"));
Company nanjingCom = new ConcreteCompany("南京办事处");
nanjingCom.add(new FinanceDepartment("南京办事处财务部"));
nanjingCom.add(new HRDepartment("南京办事处人力资源部"));
huadongCom.add(hangzhouCom);
huadongCom.add(nanjingCom);
root.add(shandongCom);
root.add(huadongCom);
root.display(0);
}
}