設計模式Demo
阿新 • • 發佈:2018-11-07
設計模式學習程式碼
裝飾模式
public class DecoratorPattern {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA a = new ConcreteDecoratorA();
ConcreteDecoratorB b = new ConcreteDecoratorB();
a.SetComponent(c);
b. SetComponent(a);
b.Operation();
}
}
abstract class Component {
public abstract void Operation();
}
class ConcreteComponent extends Component {
@Override
public void Operation() {
System.out.println("具體物件的操作類");
}
}
abstract class Decorator extends Component {
protected Component component;
public void SetComponent(Component component) {
this.component = component;
}
@Override
public void Operation(){
if (component!=null){
component.Operation();
}
}
}
class ConcreteDecoratorA extends Decorator {
private String addedState;
@Override
public void Operation(){
super.Operation();
addedState = "New State";
System.out.println("具體裝飾物件A的操作類");
}
}
class ConcreteDecoratorB extends Decorator {
@Override
public void Operation(){
super.Operation();
AddedBehavior();
System.out.println("具體裝飾物件B的操作類");
}
private void AddedBehavior(){
}
}
策略模式
public class StrategyPattern {
public static void main(String[] args) {
Context context;
context = new Context(new StrategyA());
context.context();
context = new Context(new StrategyB());
context.context();
context = new Context(new StrategyC());
context.context();
}
}
//抽象演算法類
abstract class Strategy {
//演算法方法
public abstract void algorithm();
}
//具體演算法A
class StrategyA extends Strategy {
@Override
public void algorithm() {
System.out.println("演算法A實現");
}
}
//具體演算法B
class StrategyB extends Strategy {
@Override
public void algorithm() {
System.out.println("演算法B實現");
}
}
//具體演算法B
class StrategyC extends Strategy {
@Override
public void algorithm() {
System.out.println("演算法C實現");
}
}
class Context {
private Strategy strategy ;
// 策略選擇
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void context(){
strategy.algorithm();
}
}