工厂模式的实践如下。

    1. pub trait ServiceFactory<Req> {
    2. /// Responses given by the created services.
    3. type Response;
    4. /// Errors produced by the created services.
    5. type Error;
    6. /// Service factory configuration.
    7. type Config;
    8. /// The kind of `Service` created by this factory.
    9. type Service: Service<Req, Response = Self::Response, Error = Self::Error>;
    10. /// Errors potentially raised while building a service.
    11. type InitError;
    12. /// The future of the `Service` instance.
    13. type Future: Future<Output = Result<Self::Service, Self::InitError>>;
    14. /// Create and return a new service asynchronously.
    15. fn new_service(&self, cfg: Self::Config) -> Self::Future;
    16. }

    这个trait就是典型应用工厂模式的案列。实现该trait的类型可以用来生成了Service的类型。这里trait+关联类型的应用。
    抽象工厂模式实践。

    1. pub trait IntoServiceFactory<SF, Req>
    2. where
    3. SF: ServiceFactory<Req>,
    4. {
    5. /// Convert `Self` to a `ServiceFactory`
    6. fn into_factory(self) -> SF;
    7. }

    实现该trait的类型可以生成实现了ServiceFactory的类型。这里使用trait约束。
    利用trait+关联类型或者是trait约束我们轻易实现工厂模式。这里我们需要探究的是那种方式更好。