大多使用在避免未經授權,認證就對目標物件進行存取,如此一來避免資源的浪費,也對於使用者權限範圍限制.
例如:
Facebook須登入後,才會依登入的使用者身分,給予該使用者有限的資訊擷取
class SubjectAccessor以上面的例子來說:
{
public interface ISubject
{
string Request ( );
}
private class Subject
{
public string Request( )
{
return "Subject Request " + "Choose left door\n";
}
}
public class ProtectionProxy : ISubject
{
// An authentication proxy first asks for a password
Subject subject;
string password = "12345";
public string Authenticate (string supplied)
{
if (supplied!=password)
return "Protection Proxy: No access";
else
subject = new Subject( );
return "Protection Proxy: Authenticated";
}
public string Request( )
{
if (subject==null)
return "Protection Proxy: Authenticate first";
else
return "Protection Proxy: Call to "+subject.Request( );
}
}
}
目標是要存取Subject class的物件
而要對外提供存取subject物件使用了ISubject 介面,並指定公開Request()給外部存取
為了要提供授權機制,加入了ProtectionProxy class(Proxy Pattern),並繼承ISubject實作Request(),而在讓外部存取Request()之前,要求要透過Authenticate()認證後,才實體化Subject給外部存取
而外部存取時,使用方式如下
ProtectionProxy subject = new ProtectionProxy( );參考書籍c#3.0 design pattern
(subject as ProtectionProxy).Authenticate("12345");
subject.Request( );
沒有留言:
張貼留言