工厂方法模式
UML
使用工厂类的静态方法生成对象:
Java
创建二者的共同接口:
public interface Sender { void send(); }
创建实现类:
class MailSender implements Sender { public void send() { System.out.println("this is mail sender!"); } }
class SmsSender implements Sender { public void send() { System.out.println("this is sms sender!"); } }
建工厂类:
class SenderFactory { static Sender produceMail() { return new MailSender(); } static Sender produceSms() { return new SmsSender(); } }
测试类:
public class SenderTest { public static void main(String[] args) { Sender sender = SenderFactory.produceMail(); sender.send(); } }
Scheme
不需要创建子类,创建不同的函数来包装不同的行为,把函数作为参数传入:
(define (send fn) ;; fn (fn) #t) (define (sms) (begin (display "this is sms sender!") (newline))) (define (email) (begin (display "this is email sender!") (newline)))
测试代码:
(send sms) ;; => this is sms sender! ;; Value: #t