1 import java.util.ArrayList;
2
3 class Manager
4 {
5 private String name; //经理的名字
6 public Manager(String string) {
7 name=string;
8 }
9 public void update(String id)
10 {
11 System.out.println("哈哈"+id+"房子已经被买了,好开心");
12 }
13
14
15 }
16 //抽象房子
17 abstract class House
18 {
19 private String id;
20 private int price;
21 private int status=0;// status=0没有被卖掉
22 private ArrayList<Manager> m=new ArrayList<Manager>();
23 public void setStatus()
24 {
25 status=1; //卖房子了
26 for(Manager ma:m)
27 {
28 ma.update(id);
29 }
30 }
31 public House(String id,int price)
32 {
33 this.id=id;
34 this.price=price;
35 }
36 public void addObserver(Manager ma)
37 {
38 m.add(ma);
39 }
40
41
42 }
43 //具体房子
44 class BigHouse extends House
45 {
46 public BigHouse(String id, int price) {
47 super(id, price);
48 // TODO Auto-generated constructor stub
49 }
50
51 public void method()
52 {
53 System.out.println("BigHouse");
54
55 }
56 }
57 //具体房子
58 class smallHouse extends House
59 {
60
61 public smallHouse(String id, int price) {
62 super(id, price);
63 // TODO Auto-generated constructor stub
64 }
65
66 public void met()
67 {
68 System.out.println("smallHouse");
69 }
70 }
71 //工厂接口
72 interface factory
73 {
74 public House getInstance(String id,int price);
75
76 }
77 //大房子工厂
78 class BigFactory implements factory
79 {
80
81 @Override
82 public House getInstance(String id, int price) {
83 // TODO Auto-generated method stub
84 return new BigHouse(id,price);
85 }
86
87
88 }
89 class smallFactory implements factory
90 {
91
92 @Override
93 public House getInstance(String id, int price) {
94 // TODO Auto-generated method stub
95 return new smallHouse(id,price);
96 }
97
98
99
100 }
101
102
103 public class 设计模式1 {
104
105 /**
106 * @param args
107 */
108 public static void main(String[] args) {
109 // TODO Auto-generated method stub
110 //创建一大房子对象
111 House h1=new BigFactory().getInstance("0001", 10000000);
112 //一个小房子对象
113 ((BigHouse) h1).method();
114 House h2=new smallFactory().getInstance("333", 100);
115 Manager ma=new Manager("zhangsan");
116 h2.addObserver(ma);
117 h2.setStatus();
118
119
120
121
122
123 //卖掉
124
125
126
127
128 }
129
130 }
http://blog.csdn.net/lovelion/article/details/7430515