常见设计模式代码二
Posted xiaoxiannvblog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常见设计模式代码二相关的知识,希望对你有一定的参考价值。
四 代理模式
类图:
代码:
抽象方法:
public abstract class AbstractObject {
public abstract void option();
}
具体实现:
public class RealObject extends AbstractObject {
@Override
public void option() {
System.out.println("real method...");
}
}
代理:
public class ProxyObject extends AbstractObject {
private RealObject realObject=new RealObject();
@Override
public void option() {
System.out.println("执行任务前 检查....");
realObject.option();
}
}
五 观察者模式
观察者模式类图 :
观察者操作抽象
public interface Observer {
public void update();
}
观察者A B
public class ObserverA implements Observer{
@Override
public void update() {
System.out.println("ObserverA 执行操作");
}
}
public class ObserverB implements Observer {
@Override
public void update() {
System.out.println("ObserverB 执行操作");
}
}
目标操作抽象:
public interface Subject {
public void option();
}
目标更新操作:
public class MySubject implements Subject{
@Override
public void option() {
System.out.println("目标对象执行操作通知观察者.....");
}
}
通知观察者:
public abstract class AbstractSubject implements Subject {
private Vector<Observer> observers = new Vector<Observer>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void delObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
客户端调用:
AbstractSubject subject = new MySubject();
subject.add(new ObserverA());
subject.add(new ObserverB());
subject.operation();
六 策略模式
策略模式类图
策略模式代码
抽象策略
public interface MemberStrategy {
public double calcPrice(double booksPrice);
}
普通会员:
public class CommonVip implements MemberStrategy{
@Override
public double calcPrice(double booksPrice) {
System.out.println("普通会员....");
return booksPrice*0.9;
}
}
高级会员:
public class AdvancedVip implements MemberStrategy {
@Override
public double calcPrice(double booksPrice) {
System.out.println("高级会员...");
return booksPrice*0.8;
}
}
计算价格类:
public class Price {
private MemberStrategy memberStrategy;
public Price(MemberStrategy memberStrategy) {
this.memberStrategy = memberStrategy;
}
public double quote(double bookPrice) {
return memberStrategy.calcPrice(bookPrice);
}
}
以上是关于常见设计模式代码二的主要内容,如果未能解决你的问题,请参考以下文章