Skip to content

Instantly share code, notes, and snippets.

@eccyan
Last active August 29, 2015 14:21
Show Gist options
  • Save eccyan/2a0b16c7c97279d54254 to your computer and use it in GitHub Desktop.
Save eccyan/2a0b16c7c97279d54254 to your computer and use it in GitHub Desktop.
オ・ト・ナのカプセル化再入門 ref: http://qiita.com/eccyan/items/a14097b75e0cf6d924f3
package shape;
// Subsystem
public Line extends Shape {
public void draw(Point from, Point to) { ... }
}
// Subsystem
public Circle extends Shape {
public void draw(Point point) { ... }
}
package widget;
// Facade
public AwesomeWindow {
private Line line = new Line();
private Circle circle = new Circle();
public void draw() {
Display display = Display.getInstance();
line.draw(display.getCornerTopLeft(), display.getCornerTopRight()));
line.draw(display.getCornerTopLeft(), display.getCornerBottomLeft()));
line.draw(display.getCornerTopRight(), display.getCornerBottomRight()));
line.draw(display.getCornerBottomRight(), display.getCornerBottomLeft()));
circle.draw(display.getCenter());
}
}
package assembly;
// パッケージ内からのみアクセス許可
class Processor { ... }
class Memory { ... }
class Display { ... }
public class Phone {
public static class Factory {
public static Phone create(ProcessorType processorType, int memorySize) {
return new Phone(new Processor(processorType), new Memory(memorySize));
}
}
}
private Processor processor;
private Memory memory;
private Display display;
Phone(ProcessorType processortype, int memorySize) {
processor = new Processor(processortype);
memory = new Memory(memorySize);
display = new Display();
}
public render() {
processor.render(display, memory);
}
// Setter 等の状態変更はさせてはならない
...
}
package person;
class Name { ... }
class Address { ... }
class Interest { ... }
public class Profile {
public static class Factory {
...
}
private boolean requiredName;
private Name name;
private List<Interest> interests;
private List<Address> addresses;
// 興味が追加出来るか
public boolean canAddInterest() {
return interests.size() > 5;
}
// 名前を必須項目にするか
public void setRequiredName(boolean required) {
requiredName = required;
}
// プロフィールが完全か
public boolean hasCompleted() {
return (requiredName && name != null) && interests.size() > 0 && addresses.size() > 0;
}
public void addInterest(String interestText) {
if (!canAddInterest()) { throw new Exception(); }
interests.add(new Interest(interestText));
}
...
}
package zoo;
interface Animal {
String getSound();
}
public class Animal {
public static class Factory {
...
}
private List<Animal> animals;
// クライアントにとって解りやすいインタフェースを提供する
public void makeSounds() {
for (Animal animal : animals) {
System.out.println(animal.getSound())
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment