public class Pay {
public void request(String channel) {
if (channel.equals("ALIPAY")) {
// call the alipay sdk api
} else if (channel.equals("WEIXIN")) {
// call the weixin adk api
}
}
}
public interface IPay {
void request();
}
public class WeixinPay implements IPay {
@Override
public void request() {
// call the weixin pay sdk api
}
}
public class Alipay implements IPay {
@Override
public void request() {
// call the alipay sdk api
}
}
然后 pay方法重构如下:
public class Pay {
public void request(String channel) {
factory(channel).request();
}
public IPay factory(String channel) {
if (channel.equals("ALIPAY")) {
return new Alipay();
}
return new WeixinPay();
}
}
public abstract class Shape {
protected int x, y;
protected String color;
public Shape(int x, int y, String color) {
this.x = x;
this.y = y;
this.color = color;
}
public abstract void draw();
public void move(int newX, int newY) {
this.x = newX;
this.y = newY;
System.out.println("Move shape to: " + x + ", " + y);
}
}
然后编写子类:
public class Circle extends Shape {
private int radius;
public Circle(int x, int y, String color, int radius) {
super(x, y, color);
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing circle at: (" + x + ", " + y + ") with radius " + radius + " and color " + color);
}
}
在来编写更多的子类:
public class Rectangle extends Shape {
private int width, height;
public Rectangle(int x, int y, String color, int width, int height) {
super(x, y, color);
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing rectangle at: (" + x + ", " + y + ") with width " + width + " and height " + height + " and color " + color);
}
}