工厂模式
把对象创建和使用分开。
public interface PaymentService{ public void pay(); } public class AliPayService implements PaymentService{ @Override public void pay(){ System.out.println("支付宝支付..."); } } public class WeChatService implements PaymentService{ @Override public void pay(){ System.out.println("微信支付..."); } } public class PayMentFactory{ public static PaymentService getPaymentService(Integer payType){ PaymentService paymentService = null; switch(payType){ case 0: paymentService = new AliPayService(); break; case 1: paymentService = new WeChatService(); break; } return paymentService; } } public class Test{ public static void main(String[] args){ PaymentService paymentService = PayMentFactory.getPaymentService(1); paymentService.pay(); } }