Skip to content

Instantly share code, notes, and snippets.

@kenji-andoh
Last active March 28, 2017 01:22
Show Gist options
  • Save kenji-andoh/57c30164044db5ceb94a3cc89cdee2f7 to your computer and use it in GitHub Desktop.
Save kenji-andoh/57c30164044db5ceb94a3cc89cdee2f7 to your computer and use it in GitHub Desktop.
immutable 解説のためのコード断片
// クラスの内部状態が Mutable だったら
// あるクラスの"設定" を示す
class SomeSettings
{
//あるクラスの何らかの動作モード
public enum BehaviourMode { A,B };
//設定のモードの値
public BehaviourMode Mode{ get;set;}
}
// SomeSettings を内部的に使用するクラス
class SomeClass
{
// Mutable な内部状態を public にしちゃった
public SomeSettings Settings{ get; private set;}
public SomeClass( SomeSettings settings )
{
Settings = settings;
}
//設定のモードによって振る舞いが変わる。
public void someMethod(){ /*...*/}
}
class SomeClassUser
{
// おやここでも mutable な内部状態を公開しちゃってる
public readonly SomeClass impl = new SomeClass( new SomeSettings{ Mode = SoumeSettings.BehaviourMode.A } );
public void someMethod()
{
// impl.someMethod() はモードAで実行するはずだ。
// なにしろ自分で A モードとして初期化したんだからな。
// 絶対だ。
impl.someMethod();
}
}
System.String str = "string";
str.ToUpper(); //str の内容は変化しない
str = str.ToUpper(); //( str == "STRING" )
System.String s1 = "apple" + "pen";
System.String s2 = String.Concat("apple","pen"); //2項の + 演算と同じ
MyString s1 = new MyString("apple");
MyString s2 = s1;
s2.Append("pen"); //あれ? s1 も s2 も "applepen" だ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment