简单工厂模式
trait Login {
fn verify(&self, name: String, password: String) -> bool;
}
enum LoginType {
Domain,
Password,
}
struct DomainLogin {}
impl Login for DomainLogin {
fn verify(&self, name: String, password: String) -> bool {
/**
* do some work
* */
println!("login via domain");
true
}
}
struct PasswordLogin {}
impl Login for PasswordLogin {
fn verify(&self, name: String, password: String) -> bool {
/**
* do some work
* */
println!("login via password");
true
}
}
struct LoginManager;
impl LoginManager {
fn factory(type_: &LoginType) -> Box<dyn Login> {
match type_ {
LoginType::Domain => Box::new(DomainLogin{}),
LoginType::Password => Box::new(PasswordLogin{}),
}
}
}
fn main() {
let login = LoginManager::factory(&LoginType::Domain);
login.verify("name".to_string(), "password".to_string());
let login = LoginManager::factory(&LoginType::Password);
login.verify("name".to_string(), "password".to_string());
}