首先是不用門面模式來買這些東西:
- class CoatFactory{
- class Coat{}
- public Coat saleCoat(){
- return new Coat();
- }
- }
- class ComputerFactory{
- class Computer{}
- public Computer saleComputer(){
- return new Computer();
- }
- }
- class MobileFactory{
- class Mobile{}
- public Mobile saleMobile(){
- return new Mobile();
- }
- }
- public class Test{
- public static void main(String[] args){
- //買衣服
- CoatFactory coatFactory = new CoatFactory();
- System.out.println(coatFactory.saleCoat().getClass().getName());
- //買電腦
- ComputerFactory computerFactory = new ComputerFactory();
- System.out.println(computerFactory.saleComputer().getClass().getName());
- //買手機
- MobileFactory mobileFactory = new MobileFactory();
- System.out.println(mobileFactory.saleMobile().getClass().getName());
- }
- }
上面的代碼裏面,我們必須直接和生產者打交道,這樣會很麻煩,我們需要一個統一的接口,可以得到所有這些東西,那麼就用到了facade模式,下面就是用fadace模式實現的代碼:
- package facade;
- class Coat{}
- class Computer{}
- class Mobile{}
- class CoatFactory{
- public Coat saleCoat(){
- return new Coat();
- }
- }
- class ComputerFactory{
- public Computer saleComputer(){
- return new Computer();
- }
- }
- class MobileFactory{
- public Mobile saleMobile(){
- return new Mobile();
- }
- }
- class Store
- {
- public Coat saleCoat()
- {
- CoatFactory coatFactory = new CoatFactory();
- return coatFactory.saleCoat();
- }
- public Computer saleComputer()
- {
- ComputerFactory computerFactory = new ComputerFactory();
- return computerFactory.saleComputer();
- }
- public Mobile saleMobile()
- {
- MobileFactory mobileFactory = new MobileFactory();
- return mobileFactory.saleMobile();
- }
- }
- public class Test{
- public static void main(String[] args){
- Store store =new Store();
- //買衣服
- System.out.println(store.saleCoat().getClass().getName());
- //買電腦
- System.out.println(store.saleComputer().getClass().getName());
- //買手機
- System.out.println(store.saleMobile().getClass().getName());
- }
- }
在這裏,我們想要得到各種商品,只需要和Store這個類打交道就行了,不需要直接和廠家聯繫,降低了客戶端代碼和生產者之間的耦合,當生產者發生變化的時候,只需要更改Store這個類,而不必改客戶端。舉一個大家可能會經常用到的例子吧,數據庫連接,現在數據庫廠商非常多,比如oracle,sqlserver,mysql等等,當我們想要一個數據庫連接對象的時候,需要進行一系列操作,客戶端希望告訴一個類用戶名,密碼,url和數據庫廠商,就直接返回一個數據庫連接對象,那麼就可以使用fadace模式,這個模式中的Store的形式如下:
- class DatabaseSeller{
- public Oracle getOracleObject(String username,String password,String url){}
- public SqlServer getSqlServerObject(String username,String password,String url){}
- public MySql getMySqlObject(String username,String password,String url){}
- }
這樣做的好處就是隱藏了數據庫連接操作的細節,用戶只關心自己的業務邏輯就行了,數據庫連接這些與業務邏輯無關的操作就讓其它類來做就行了。