Bridge模式

简述:

Bridge模式

Bridge模式_第1张图片

与工厂方法不同的是, 其具体的方法实现可以被共享

如下述例子里月饼馅料制作的实现可以被共享


例子:

设计了一个制作月饼的样例,

制作两种月饼一种是椰蓉的,一种是豆沙的,分别使用两个类一个是CoconutMoonCakeImp类,以及BeanPastedMoonCake都实现了MoonCakeImp接口

还使用了一个SuperMoonCake继承自MoonCake,重写了RefineMoonCake()函数,此函数用来表示加工不同类型月饼的过程


代码:

MoonCakeImp.java 用于制作不同馅料的接口

package design_pattern.bridge;

public interface MoonCakeImp {
	String MakeMoonCake();
}

CoconutMoonCakeImp.java 制作椰蓉月饼行为实现类

package design_pattern.bridge;

public class CoconutMoonCakeImp implements MoonCakeImp {
	@Override
	public String MakeMoonCake() {
		return "Coconut Moon Cake";
	}
}


BeanPastedMoonCakeImp.java 制作豆沙月饼行为实现类

package design_pattern.bridge;

public class BeanPastedMoonCake implements MoonCakeImp{
	@Override
	public String MakeMoonCake() {
		return "Bean Pasted Moon Cake";
	}
}

MoonCake.java 抽象类月饼, 可视为月饼原料和月饼制作实现的抽象

package design_pattern.bridge;

public abstract class MoonCake {
	protected MoonCakeImp moonCakeImp;
	MoonCake(MoonCakeImp moonCakeImp) {
		this.moonCakeImp = moonCakeImp;
	}
	public void setMoonCakeImp(MoonCakeImp moonCakeImp) {
		this.moonCakeImp = moonCakeImp;
	}
	abstract public void RefineMoonCake();
}

SmallMoonCake.java 小型月饼,继承MoonCake抽象类

package design_pattern.bridge;

public class SmallMoonCake extends MoonCake {
	protected int size = 1;
	SmallMoonCake(MoonCakeImp moonCakeImp) {
		super(moonCakeImp);
	}

	@Override
	public void RefineMoonCake() {
		System.out.println(moonCakeImp.MakeMoonCake() 
				+ "'s size is " + size);
	}
}

SuperMoonCake.java 大型月饼,继承MoonCake抽象类

package design_pattern.bridge;

//use size 10 to represent the size of the moon cake
public class SuperMoonCake extends MoonCake {
	protected int size = 10;
	SuperMoonCake(MoonCakeImp moonCakeImp) {
		super(moonCakeImp);
	}
	@Override
	public void RefineMoonCake() {
		System.out.println(moonCakeImp.MakeMoonCake() 
				+ "'s size is " + size);
	}
}

TestBridge.java 测试类

package design_pattern.bridge;

public class TestBridge {
	public static void main(String[] args) {
		//Make Super Coconut Moon Cake
		MoonCakeImp coconutCakeImp = new CoconutMoonCakeImp();
		SuperMoonCake superCoconutMoonCake = new SuperMoonCake(coconutCakeImp);
		superCoconutMoonCake.RefineMoonCake();
		//Make Super Bean Pasted Moon Cake;
		MoonCakeImp beanPastedMoonCake = new BeanPastedMoonCake();
		SmallMoonCake superBeanPastedMoonCake = new SmallMoonCake(beanPastedMoonCake);
		superBeanPastedMoonCake.RefineMoonCake();
	}
}

输出:




你可能感兴趣的:(Bridge模式)