例如:下面的接口定义了组件的功能:发送消息;类Transceiver实现了该接口;而其子类Pool只是管理多个Transceiver对象,而没有提供自己的接口实现。建议使用组合方式,而不是继承! public interface ITransceiver{0 Z, [) @* N7 ^
public abstract send(String msg);
) s/ W4 | z0 A0 J" E }+ B Z n S3 e2 E# N
public class Transceiver implements ITransceiver {
9 A5 K' |6 e$ C9 F public send(String msg){; b a/ j' ~& I' H. x; z
System.out.println(msg);- l" m! A5 \! k- U1 B& ^" e" y
}- g$ `( X; ?* Q2 ^6 f! P
}
8 C9 ?$ t6 M- p2 J, h& z) r- j //使用继承方式的实现
5 v* P- O( D F" ~3 X public class Pool extends Transceiver{/ l6 X* Z3 ~! q
private List pool = new Vector();+ K( }% H% Y$ |
public void add(Transceiver aTransceiver){
& g; [3 c! H: Q/ _1 t! ]( } w# H pool.add(aTransceiver); g" G- v0 Q* o& D; `+ {1 s" U8 Q+ H
}
y' ?% P: A! r" F" x! ` public Transceiver get(int index){. m- f& v( R& f# q: ]
pool.get(index);& b* V; ]1 `2 g6 y
}2 f: o, D4 k. l- |3 T. p+ b
}# }( t! `4 O. }% }
//使用组合方式的实现
* V7 ^' i$ v* B" m public class Pool {
. z4 z& g8 g3 l4 O2 H/ x9 u private List pool = new Vector();
7 \1 _: l% \$ w3 o, Y8 q public void add(Transceiver aTransceiver){4 k, L7 p% o5 n7 s
pool.add(aTransceiver);7 q4 |( p2 D. C# M7 I, z) H
}. m6 ]# n* S7 v6 B1 Q1 C# V
public Transceiver get(int index){
6 }, Q- p1 E' Y( `( E9 G W pool.get(index);
# H5 X% o, o# E- p9 s, v+ Q }
) j; |) x! ?$ K+ F2 D/ s6 A }# `1 {6 i) }. |0 G0 j
拆分过大的类6 y+ B+ W6 [! Z" P2 n- o$ n# g3 p) N; m
如果一个类有太多的方法(超过50个),那么它可能要做的工作太多,我们应该试着将它的功能拆分到不同的类中,类似于规则四。; T; r7 {# ]" Q9 L5 @5 Q2 B
作用截然不同的对象应该拆分7 x9 K7 [& y7 S6 | ]
在构建的过程中,你有时会遇到这样的问题:对同样的数据,有不同的视图。某些属性描述的是数据结构怎样生成,而某些属性描述的是数据结构本身。最好将这两个视图拆分到不同的类中,从类名上就可以区分出不同视图的作用。) e, {5 a2 l0 h
类的域、方法也应该有同样的考虑!
1 G s( M6 x$ I) E" L5 L 尽量减少对参数的隐含传递- ~: g, H* q& _2 X; ], {# A
两个方法处理类内部同一个数据(域),并不意味着它们就是对该数据(域)做处理。许多时候,该数据(域)应该作为方法的参输入数,而不是直接存取,在工具类的设计中尤其应该注意。例如:
+ i M! Y" q q public class Test{
3 |# B8 e. z3 N private List pool = new Vector();4 Y5 n3 t2 L$ q2 k3 j i( @
public void testAdd(String str){* P# O6 T$ x9 K! \0 Y! U
pool.add(str);7 p2 }8 b( u7 a
}
2 M7 ], w! e" F5 r9 L2 o public Object testGet(int index){
) k5 m4 g2 w1 j3 `$ Q( ~5 Q' ^& m pool.get(index);6 o4 ^9 {$ }3 o& B0 N! C9 o6 X
}
3 } f7 f7 B5 p! M: v6 s }
! D# o3 _: |* f. w 两个方法都对List对象pool做了操作,但是,实际上,我们可能只是想对List接口的不同实现Vector、ArrayList等做存取测试。所以,代码应该这样写:
- A \3 P3 V+ M w* U public class Test{& {# w+ x6 A3 l+ P# x) |7 ]
private List pool = new Vector();! B, M* Q% D) l" n
public void testAdd(List pool, String str){8 Z; M' B0 W6 }) H, z6 I& w
pool.add(str);' ?- x8 w8 h/ |* J8 _1 t& s! k% @& J
}
* K6 L0 u# r$ C2 ^; I& Z public Object testGet(List pool, int index){- `# W8 o- h, ^, o m& _8 I
pool.get(index); |