public static void main(String[] args) {
Computer computer = new Computer();
computer.put();
}
}
class CPU {
public void work(){
//复杂的操作
System.out.println("CPU is working!");
}
}
class Disk {
public void put(){
//复杂的操作
System.out.println("put in disk!");
}
}
//外观类,隐藏了系统的复杂性,提供简化的方法(访问系统的接口)
//客户端不需要知道系统内部的复杂联系
class Computer {
private CPU cpu;
private Disk disk;
public Computer(){
cpu = new CPU();
disk = new Disk();
}
public void work(){
cpu.work();
}
public void put(){
disk.put();
}
}
public static void main(String[] args) {
Person person = new Person("小明");
person.addFriends(new Person("小红"));
person.addFriends(new Person("小白"));
System.out.println(person.getFriends());
}
}
class Person {
private String name;
//包含自己的对象组
private List<Person> friends = new ArrayList<Person>();
public Person(String name){
this.name = name;
}
public Person addFriends(Person p){
friends.add(p);
return this;
}
public String getName(){
return this.name;
}
public List<Person> getFriends(){
return this.friends;
}
public String toString(){
return this.name;
}
}
public static void main(String[] args) {
//red Circle默认存在,所以拿的时候不用new
Circle circle = CircleFactory.getCircle("red");
circle.draw();
for(int i=0;i<2;i++) {
//第一次拿的时候需要new green Circle,第二次拿的时候不用new
circle = CircleFactory.getCircle("green");
circle.draw();
}
}
}
class Circle {
private String color;
public Circle(String color){
this.color = color;
}
public void draw(){
System.out.println(color+" Circle!");
}
}
class CircleFactory {
private static final HashMap<String, Circle> circleMap = new HashMap<String, Circle>();
static {
//初始化,存放red Circle
circleMap.put("red", new Circle("red"));
}
public static Circle getCircle(String color) {
Circle circle = (Circle)circleMap.get(color);
//Map如果不存在该颜色的Circle,则新建
if(circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("new a circle of color: "+color);
}
//如果存在,则返回Map中的对象
return circle;
}
}