Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Last active October 30, 2018 01:51
Show Gist options
  • Save j5ik2o/df2520fa778b0527a643eb5cf6d5fe57 to your computer and use it in GitHub Desktop.
Save j5ik2o/df2520fa778b0527a643eb5cf6d5fe57 to your computer and use it in GitHub Desktop.
// 絵の具を表すオブジェクト(副作用が伴う可変オブジェクト)
public class Paint {
private int volume;
private PigmentColor pigmentColor;
// getter, setter 省略
public Paint(PigmentColor pigmentColor, int volume) {
this.volume = volume;
this.pigmentColor = pigmentColor;
}
// 副作用を起こす命令として実装
public void mixIn(Paint other) {
volume = volume + other.volume;
double raito = other.volume / volume;
// 顔料の更新処理を関数化して副作用を起こさないようにし、
// 関数で得た新しいpigmentColorを入れ替える処理をmixInメソッドで行う。
pigmentColor = pigmentColor.mixedWith(other.pigmentColor, ratio);
}
}
// 顔料を表すバリューオブジェクト(副作用が伴わない不変オブジェクト)
public final class PigmentColor {
private final int red;
private final int yellow;
private final int blue;
// getter省略
public PigmentColor(int red, int yellow, int blue) {
this.red = red;
this.yellow = yellow;
this.blue = blue;
}
// 顔料を混ぜあわせて新たな顔料を生成して返す。副作用は起こさない関数として実装する。
public PigmentColor mixedWith(PigmentColor other, double ratio) {
int red = (int)((red + other.red) / ratio);
int yellow = (int)((yellow + other.yellow) / ratio);
int blue = (int)((blue + other.blue) / ratio);
return new PigmentColor(red, yellow, blue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment