1.工厂类一定需要将构造方法私有化吗,为什么?
不一定。看源码中有public修饰的,原因自己描述不了
2.用工厂模式设计支付业务场景,包含跨境支付,支付宝、微信、银联支付,并画出类图。
public interface IPayFactory {
public IPayMethod createPayMethod();
}
public interface IPayMethod {
public void prePay();
public void pay();
public void afterPay();
}
public class ZfbPayMethod implements IPayMethod {
@Override
public void prePay() {
System.out.println("支付宝支付前准备");
}
@Override
public void pay() {
System.out.println("支付宝支付");
}
@Override
public void afterPay() {
System.out.println("支付宝支付后操作:向用户推送短信");
}
}
public class WechatPayMethod implements IPayMethod {
@Override
public void prePay() {
System.out.println("微信支付前准备");
}
@Override
public void pay() {
System.out.println("微信支付");
}
@Override
public void afterPay() {
System.out.println("微信支付后操作:向用户推送短信");
}
}
public class UnionPayMethod implements IPayMethod {
@Override
public void prePay() {
System.out.println("银联支付前准备");
}
@Override
public void pay() {
System.out.println("银联支付");
}
@Override
public void afterPay() {
System.out.println("银联支付后操作:向用户推送短信");
}
}
public class InternationalPayMethod implements IPayMethod {
@Override
public void prePay() {
System.out.println("跨境支付前准备");
}
@Override
public void pay() {
System.out.println("跨境支付");
}
@Override
public void afterPay() {
System.out.println("跨境支付后操作:向用户推送短信");
}
}
public class ZfbPayFactory implements IPayFactory {
@Override
public IPayMethod createPayMethod() {
return new ZfbPayMethod();
}
}
public class Test {
public static void main(String[] args) {
IPayFactory factory = new ZfbPayFactory();
IPayMethod payMethod = factory.createPayMethod();
payMethod.prePay();
payMethod.pay();
payMethod.afterPay();
}
}