设计模式之facade模式

来源:互联网 发布:阿里云怎么安装软件 编辑:程序博客网 时间:2024/05/20 07:52

小贴士:大多素工作还是需要有底层系统实现。facade模式提供了一组更容易理解的方法,这些方法使用底层系统来实现新定义的函数。

关键特征:

意图:希望简化原有系统的使用方式。需要定义自己的接口。

问题:只需要使用某个复杂系统的子集,或者,以一种特殊的方式与系统交互。

解决方案:facade为原有系统的客户提供了一个新的接口。

参与者与协作者:为客户提供的一个简化接口,是系统更容易使用。参与者和协作者是接口本身和各个子系统。

效果:facade模式简化了对所需子系统的使用过程。但是,由于facade并不完整,因此客户可能无法使用某些功能。

实现:1、定义一个(或多个)具备所需接口的新类。2、让新的类使用原有的系统。

代码示例(dofactory)

贷款抵押应用程序组件(a large subsystem of classes measuring the creditworthyness of an applicant)
如何provides a simplified interface给这个组件?

//外观类
public class Mortgage
{
    
private Bank bank = new Bank();
    
private Loan loan = new Loan();
    
private Credit credit = new Credit();

    
public bool IsEligible(Customer cust, int amount)
    {
        Console.WriteLine(
"{0} applies for {1:C} loan\n",
          cust.Name, amount);

        
bool eligible = true;

        
if (!bank.HasSufficientSavings(cust, amount))
        {
            eligible 
= false;
        }
        
else if (!loan.HasNoBadLoans(cust))
        {
            eligible 
= false;
        }
        
else if (!credit.HasGoodCredit(cust))
        {
            eligible 
= false;
        }

        
return eligible;
    }
}

//银行子系统
public class Bank
{
    
public bool HasSufficientSavings(Customer c, int amount)
    {
        Console.WriteLine(
"Check bank for " + c.Name);
        
return true;
    }
}

//信用证子系统
public class Credit
{
    
public bool HasGoodCredit(Customer c)
    {
        Console.WriteLine(
"Check credit for " + c.Name);
        
return true;
    }
}

//贷款子系统
public class Loan
{
    
public bool HasNoBadLoans(Customer c)
    {
        Console.WriteLine(
"Check loans for " + c.Name);
        
return true;
    }
}

//顾客类
public class Customer
{
    
private string name;

    
public Customer(string name)
    {
        
this.name = name;
    }

    
public string Name
    {
        
get { return name; }
    }
}

//客户程序类
public class MainApp
{
    
public static void Main()
    {
        
//外观
        Mortgage mortgage = new Mortgage();

        Customer customer 
= new Customer("Ann McKinsey");
        
bool eligable = mortgage.IsEligible(customer, 125000);

        Console.WriteLine(
"\n" + customer.Name +
            
" has been " + (eligable ? "Approved" : "Rejected")); 
        Console.ReadLine();
    }
}

图:


总结

Facade设计模式更注重从架构的层次去看整个系统,而不是单个类的层次。Facade很多时候更是一种架构设计模式。
Facade更注重简化接口,Adapter模式注重转换接口,Bridge模式注重分离接口(抽象)与其实现,Decorator模式注重稳定接口的前提下为对象扩展功能。

0 0
原创粉丝点击