工厂模式的实践如下。
pub trait ServiceFactory<Req> {
/// Responses given by the created services.
type Response;
/// Errors produced by the created services.
type Error;
/// Service factory configuration.
type Config;
/// The kind of `Service` created by this factory.
type Service: Service<Req, Response = Self::Response, Error = Self::Error>;
/// Errors potentially raised while building a service.
type InitError;
/// The future of the `Service` instance.
type Future: Future<Output = Result<Self::Service, Self::InitError>>;
/// Create and return a new service asynchronously.
fn new_service(&self, cfg: Self::Config) -> Self::Future;
}
这个trait就是典型应用工厂模式的案列。实现该trait的类型可以用来生成了Service的类型。这里trait+关联类型的应用。
抽象工厂模式实践。
pub trait IntoServiceFactory<SF, Req>
where
SF: ServiceFactory<Req>,
{
/// Convert `Self` to a `ServiceFactory`
fn into_factory(self) -> SF;
}
实现该trait的类型可以生成实现了ServiceFactory的类型。这里使用trait约束。
利用trait+关联类型或者是trait约束我们轻易实现工厂模式。这里我们需要探究的是那种方式更好。