talk is cheap show me the code
适配器模式
- 类适配器模式
//目标对象
interface Target{
void doA();
void doB();
}
class ExA(){
public void doA(){
system.out.println("ex A");
}
}
//适配器负责将ExA中的方法适配到Target的doA中
class Adapter extends ExA implements Target{
public void doB(){
system.out.println(" BB")
}
}
- 接口适配器模式
interface Target{
void doA();
void doB();
}
class AbstractAdapter implements Target{
void doA(){
}
void doB(){
}
}
//只需适配自己的方法就行
class ExA extends AbstractAdapter {
void doA(){
system.out.printl("ExA");
}
}
class ExB extends AbstractAdapter {
void doB(){
system.out.printl("ExB");
}
}
- 对象适配器模式
interface Target{
void doA();
void doB();
}
class Source{
void doSomething(){
system.out.println("this is source");
}
}
class WrapperAdapter implements Target{
private Source source;
WrapperAdapter(Source source){
this.source = source;
}
void doA(){
source.doSomething();
}
void doB(){
//doAnything
}
}
桥接模式
interface Target {
void doA():
}
class Ta implements Target{
public void doA(){
system.out.printl("hahaA");
}
class Tb implements Target{
public void doA(){
system.out.printl("hahaB");
}
public abstract class Bridge{
protected Target target;
abstract void doA();
public Bridge setTarget(Target target){
this.target = target;
}
}
public class MyBridge extends Bridge{
public void doA(){
target.doA();
}
}
桥接模式只需修稿对应target实现类就行
组合模式
- 组合树例子
class TreeNode{
private String name;
private TreeNode parent;
private Vector<TreeNode> childs = new Vector();
public TreeNode(String name) {
this.name = name;
}
public void add(TreeNode treeNode){
childs.add(treeNode);
}
public Enumeration<TreeNode> getChilds(){
return childs.elements();
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode("Root");
TreeNode node1 = new TreeNode("child1");
TreeNode node2 = new TreeNode("child2");
TreeNode node3 = new TreeNode("node3");
node1.add(node3);
root.add(node1);
root.add(node2);
Enumeration<TreeNode> childs = root.getChilds();
System.out.println("");
}
装饰器模式
- 装饰器模式
interface Target(){
void doSomething();
}
class MyGirl implements Target{
public void doSomething(){
system.out.println("I LOVE U");
}
}
class Girl implements Target{
private Target target;
public Girl(Target t ){
this.target = t;
}
public void doSomething(){
system.out.println("My girls ...");
target.doSomething();
system.out.println("My girls ...");
}
}
class GoldGirl extends Girl{
GoldGirl(Target t){
super(t)
}
public void doSomething(){
system.out.println("My GoldGirl ...");
super.doSomething();
system.out.println("My GoldGirl ...");
}
}
class Test{
public static void main(Stirng[] args){
Target target = new Girl(new GoldGirl(new MyGirl()));
}
}
代理模式
- 代理模式
interface Proxyable{
void doA();
}
class Client implements Proxyable{
public void doA(){
system.out.println("i am client")
}
}
class Proxy implements Proxyable{
private Client client;
public void doA(){
system.out.println("i am proxy");
doSomething();
client.doA();
}
public void doSomething(){
}
}
网友评论