アプリケーションでロジックを分離するのに役立つパターンがいくつかあります。これにより、コードがよりクリーンで保守しやすくなります。MVP パターンは、開始するのに適したパターンです。これは、責任の 3 つの領域、つまり MVP M = モデル、V = ビュー、P = プレゼンターの定義に基づいています。インターフェイスの使用に慣れている場合は問題ありませんが、それ以外の場合は、開始するのに適しています (基本的な OO の原則を確認してください: カプセル化、抽象化、ポリモーフィズム)。MVP の基本原則は、プレゼンターにアプリケーション ロジックを配置することです。プレゼンターはインターフェイスを介してビュー (フォーム) と対話し、ビューはユーザーがプレゼンターと対話するときにプレゼンターにコールバックします (私はこれにもインターフェイスを使用します)。モデルは、ビジネス ロジックとエンティティ関係を実装するソリューションのドメイン オブジェクト階層です。
ほとんどの UI パターン (MVP、MCV など) は、同じことを行おうとしています。以下は簡単な例です。
//ビューインターフェース
interface IUserDetailsView
{
string Username{set;get;}
string FirstName{get;set;}
string LastName{get;set;}
UserDetailsPresenter Presenter{get;set;}
void DisplayMessage(string message);
}
//ビューの実装 //テキスト ボックス、ラベル、コンボなどを持つ標準の Windows フォーム。
class UserDetailsView : Form, IUserDetails
{
public string Username{set{txtUserName.text = value;}get{return txtUserName.text;}}
public string FirstName{set{txtFirstName.text = value;}get{return txtFirstName.text;}}
public string LastName{set{txtLastName.text = value;}get{return txtLastName.text;}}
Public UserDetailsPresenter Presenter{get;set;}
public void DisplayMaessage(string message)
{
MessageBox.Show(message);
}
private void saveButton_Click(object sender, EventArgs e)
{
Presenter.SaveUserDetails();
}
}
//プレゼンテーション ロジック
クラス プレゼンター UserDetailsPresenter {
//Constructor
public userDetailsPresenter(IUserDetailsView view)
{
//Hold a reference to the view interface and set the view's presnter
_view = view;
_view.Presenter = this;
}
private IUserDetailsView _view;
DisplayUser(string userName)
{
//Get the user from some service ...
UserDetails details = service.GetUser(userName);
//Display the data vioa the interface
_view.UserName = details.UserName;
_view.FirstName = details.FirstName;
_view.LastName = details.LastName;
}
public void SaveUserDetails()
{
//Get the user dryaiols from the view (i.e. the screen
UserDetails details = new UserDetails();
details.UserName = _view.UserName;
details.FirstName = _view.FirstName;
details.LastName = _view.LastName;
//Apply some business logic here (via the model)
if(!details.IsValidUserDetails())
{
_view.DisplayMessage("Some detail outlining the issues");
return;
}
//Call out to some service to save the data
service.UpdateUser(details);
}
}
//最後に、モデル
public class UserDetails
{
public UserName {get;set;}
public FirstName{get;set;}
public LastName{get;set;}
public bool IsValidUserDetails()
{
if(LastName == "Smith")
{
//We do not allow smiths, remember what happened last time ... or whatever
return false;
}
return true;
}
}
うまくいけば、これは責任がどのように分離されているかを説明しています。フォームには、表示/書式設定など以外のロジックはありません。テスト用にスタブ化することもできます。プレゼンターはビューとモデルの間のメディエーターであり、サービスを呼び出します。モデルはビジネス ロジックを実装します。すでに示唆されているように、このパターンにはバリエーションがあり、コードを少しスリムで柔軟にすることができますが、基本原則の概要は次のとおりです。これが役立つことを願っています。
:-)