Last active
August 29, 2015 14:05
-
-
Save kwatch/2f6ce3542e62a0aa7f81 to your computer and use it in GitHub Desktop.
EntityクラスとRoleクラス
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Company(name, addr) { // Entityクラス | |
this.name = name; | |
this.addr = addr; | |
// | |
this._entity = this; // 姑息な方法 | |
} | |
function Supplier(company) { // Roleクラス | |
this.__proto__ = company; | |
this.products = []; // 商品一覧 (Role固有のデータ) | |
this.history = []; // 発注履歴一覧 (Role固有のデータ) | |
this.purchase = function(product) { // 発注 (Role固有のメソッド) | |
// 通常は、ここで Entity オブジェクト (=company) のプロパティを | |
// 参照することはあっても、変更することは少ないはず。 | |
// プロパティを変更したくなったら、そのプロパティは Entity クラス | |
// ではなく Role クラスにあるべきものではないか? | |
// (RoleクラスのメソッドがRoleクラスのプロパティを変更するのは問題ない) | |
// | |
// どうしてもEntityクラスのプロパティを変更するなら、こうする | |
this._entity.name += "株式会社"; | |
}; | |
} | |
var company = new Company("海山商事"); // Entityオブジェクト | |
var supplier = new Supplier(company); // Roleオブジェクト | |
if (supplier.name !== company.name) // RoleはEntityのように扱える(参照のみ) | |
throw "Should be equal!"; | |
//supplier.name = "海山電器"; // Role経由でEntityのプロパティを設定するのは、ダメ! | |
supplier.purchase(); // Roleオブジェクトのメソッドを実行すると | |
console.log(company.name); // Entityのプロパティが変更された! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment