package com.example.demo.designpattern.strategy;
public interface Shape {
void draw();
}
package com.example.demo.designpattern.strategy;
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("画圆形");
}
}
package com.example.demo.designpattern.strategy;
public class Square implements Shape {
@Override
public void draw() {
System.out.println("画正方形");
}
}
package com.example.demo.designpattern.strategy;
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("画矩形");
}
}
package com.example.demo.designpattern.strategy;
public class Context {
private Shape shape;
public Context(Shape shape) {
this.shape = shape;
}
public void handle() {
shape.draw();
}
}
package com.example.demo.designpattern.strategy;
public class StrategyDemo {
public static void main(String[] args) {
Context context = new Context(new Circle());
context.handle();
context = new Context(new Rectangle());
context.handle();
}
}