更新時(shí)間:2022-04-02 10:28:09 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1778次
我們首先描述了簡單工廠模式:簡單工廠模式是一種類創(chuàng)建模式,也稱為靜態(tài)工廠方法模式。簡單工廠模式是一個(gè)工廠對象,它決定創(chuàng)建哪個(gè)產(chǎn)品類實(shí)例。
在登錄功能方面,如果應(yīng)用系統(tǒng)需要支持多種登錄方式,如密碼認(rèn)證和域認(rèn)證(密碼認(rèn)證通常是對數(shù)據(jù)庫中的用戶進(jìn)行驗(yàn)證,而域認(rèn)證是對微軟域中的用戶進(jìn)行驗(yàn)證)。這樣做的自然方法是創(chuàng)建一個(gè)適用于各種登錄模式的界面,如下圖所示:
public interface Login {
//validate logon
public boolean verify(String name , String password);
}
public class DomainLogin implements Login {
@Override
public boolean verify(String name, String password) {
// TODO Auto-generated method stub
/**
* Business logic
*/
return true;
}
}
public class PasswordLogin implements Login {
@Override
public boolean verify(String name, String password) {
// TODO Auto-generated method stub
/**
* Business logic
*/
return true;
}
}
我們還需要一個(gè)工廠類LoginManager來創(chuàng)建不同的登錄對象,并根據(jù)調(diào)用者的不同需求返回。如果遇到非法請求,則返回運(yùn)行時(shí)異常。
public class LoginManager {
public static Login factory(String type){
if(type.equals("password")){
return new PasswordLogin();
}else if(type.equals("passcode")){
return new DomainLogin();
}else{
/**
* It would be more appropriate to throw a custom exception here
*/
throw new RuntimeException("No login type found");
}
}
}
測試類:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String loginType = "password";
String name = "name";
String password = "password";
Login login = LoginManager.factory(loginType);
boolean bool = login.verify(name, password);
if (bool) {
/**
* Business logic
*/
} else {
/**
* Business logic
*/
}
}
}
如果不使用簡單工廠模式,驗(yàn)證登錄Servlet代碼如下(假設(shè)Test是一個(gè)Servlet,變量loginType、name、password代表客戶端傳過來的參數(shù)):
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String loginType = "password";
String name = "name";
String password = "password";
//Handling password authentication
if(loginType.equals("password")){
PasswordLogin passwordLogin = new PasswordLogin();
boolean bool = passwordLogin.verify(name, password);
if (bool) {
/**
* Business logic
*/
} else {
/**
* Business logic
*/
}
}
//Processing Domain Authentication
else if(loginType.equals("passcode")){
DomainLogin domainLogin = new DomainLogin();
boolean bool = domainLogin.verify(name, password);
if (bool) {
/**
* Business logic
*/
} else {
/**
* Business logic
*/
}
}else{
/**
* Business logic
*/
}
}
}
JAVA and Models 使用 java.text.DataFormat 類作為簡單工廠模式的典型示例。
模型的核心是工廠類。該類包含必要的邏輯判斷來決定何時(shí)創(chuàng)建登錄驗(yàn)證類的實(shí)例,而調(diào)用者則免除了直接創(chuàng)建對象的責(zé)任。簡單工廠模式通過這種方式實(shí)現(xiàn)了職責(zé)分工,當(dāng)系統(tǒng)引入新的登錄模式時(shí),不需要修改調(diào)用者。
這個(gè)工廠類集中了所有的創(chuàng)建邏輯。當(dāng)有復(fù)雜的層次結(jié)構(gòu)時(shí),所有的業(yè)務(wù)邏輯都在這個(gè)工廠類中實(shí)現(xiàn)。當(dāng)它不能工作時(shí),整個(gè)系統(tǒng)都會(huì)受到影響。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743