Design_Patterns_23

19 篇文章 0 订阅
8 篇文章 0 订阅

对象怎么来

工厂方法

抽象工厂

原型

建造者

单例

结构型模式–>对象和谁有关

享元

桥接

组合

装饰器

适配器

外观

代理

过滤

行为型模式–>对象与对象在干嘛

命令command

责任链chain

解释器interpreter

迭代子iterator

中介者mediator

观察者observer

备忘录memento

模板方法template

访问者visitor

状态state

策略strategy

工厂方法

public interface ISender {
    void Send(); 
}
--------------------------------------------------------------------------------------
public class MailSender implements ISender {
    public void Send() {
        System.out.println("this is MailSender haha");
    }

}
--------------------------------------------------------------------------------------
public class SmsSender implements ISender {
    public void Send() {
        System.out.println("this is SmsSender haha");
    }
}
--------------------------------------------------------------------------------------
public interface IProvider {
    ISender produce();
}
--------------------------------------------------------------------------------------
public class SendMailFactory implements IProvider {
    public ISender produce() {
        return new MailSender();
    }
}
--------------------------------------------------------------------------------------
public class SendSmsFactory implements IProvider {
    public ISender produce() {
        return new SmsSender();
    }
}
--------------------------------------------------------------------------------------
public class SendFactory {
    /*
     * 1.0普通工厂模式
     */
    public ISender produce(String type) {
        if ("mail".equals(type)) {
            return new MailSender();
        } else if ("sms".equals(type)) {
            return new SmsSender();
        } else {
            System.out.println("请输入正确的类型!");
            return null;
        }
    }
    /*
     * 2.0多个工厂方法模式
     */
    public ISender produceMail() {
        return new MailSender();
    }

    public ISender produceSms() {
        return new SmsSender();
    }
    /*
     * 3.0 静态工厂方法模式
     */
    public static  ISender produceMail_1() {
        return new MailSender();
    }

    public static  ISender produceSms_1() {
        return new SmsSender();
    }
    public static void main(String[] args) {
        SendFactory sendFactory = new SendFactory();
        sendFactory.produce("mail").Send();
        sendFactory.produce("sms").Send();
        // sendFactory.produce("hmn").Send();
        /** ********1******* */
        sendFactory.produceMail().Send();
        sendFactory.produceSms().Send();
        /************2***************/
        SendFactory.produceMail_1().Send();
        SendFactory.produceSms_1().Send();
        /*************3*********/
         new SendSmsFactory().produce().Send();
         new SendMailFactory().produce().Send();
    }
}

抽象工厂


原型

    public class Prototype implements Cloneable, Serializable {      
        private static final long serialVersionUID = 1L;  
        private String string;        
        private SerializableObject obj;    
        /* 浅复制 */  
        public Object clone() throws CloneNotSupportedException {  
            Prototype proto = (Prototype) super.clone();  
            return proto;  
        }  
        /* 深复制 */  
        public Object deepClone() throws IOException, ClassNotFoundException {  
           /*  写入当前对象的二进制流   
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            ObjectOutputStream oos = new ObjectOutputStream(bos);  
            oos.writeObject(this);  
             读出二进制流产生的新对象   
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());  
            ObjectInputStream ois = new ObjectInputStream(bis);  
           */  
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(bos);
            oos.writeObject(this);
            /*****************************/
            ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois=new ObjectInputStream(bis);
            
            return ois.readObject();  
        }  
        public String getString() {  
            return string;  
        }  
        public void setString(String string) {  
            this.string = string;  
        }  
        public SerializableObject getObj() {  
            return obj;  
        }  
        public void setObj(SerializableObject obj) {  
            this.obj = obj;  
        }  
        class SerializableObject implements Serializable {  
            private static final long serialVersionUID = 1L;  
        }  
    }  
----------------------------------------------------
public class Test_Prototype {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Prototype prototype = new Prototype();
        prototype.setString("kevin");
        System.out.println("prototype=" + prototype+",--"+prototype.getString());
        try {
            Prototype p = (Prototype) prototype.clone();
            System.out.println("p=" + p);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        /***************************/     
        System.out.println("befor------------prototype=" + prototype+",--"+prototype.getString());
        try {
            prototype.deepClone();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("after------------prototype=" + prototype+",--"+prototype.getString())
    }
}

建造者

------------------------------------------------------------
public class Builder {
    private List<ISender> list = new ArrayList<ISender>();
    public void produceMailSender(int count) {
        System.out.println("count=" + count);
        for (int i = 0; i < count; i++) {
            list.add(new MailSender());
        }
        System.out.println("MailSender_list" + list.size());
    }
    public void produceSmsSender(int count) {
        System.out.println("count=" + count);
        for (int i = 0; i < count; i++) {
            list.add(new SmsSender());
        }
        System.out.println("SmsSender_list" + list.size());
    }
    public List<ISender> getList() {
        return list;
    }
    public void setList(List<ISender> list) {
        this.list = list;
    }
}
------------------------------------------------------------
public class Test_builder {
    public static void main(String[] args) {
        Builder builder = new Builder();
        builder.produceMailSender(5);
        /* /************** */
        builder.produceSmsSender(10);
        /** *********************** */
        List<ISender> list = builder.getList();
        int count_MailSender=0;
        int count_SmsSender=0;
        for (ISender sender : list) {
            if (sender instanceof MailSender) {
                count_MailSender++;
            } else if (sender instanceof SmsSender) {
                count_SmsSender++;          
            }
        }
        System.out.println("count_MailSender="+count_MailSender);
        System.out.println("count_SmsSender="+count_SmsSender);
    }
}

单例

----------------------------------------------------------------------
public class Singleton {
    /* 私有构造方法,防止被实例化 */
    private Singleton() {}
    /* 此处使用一个内部类来维护单例 */
    private static class SingletonFactory {
        private static Singleton instance = new Singleton();
    }
    /* 获取实例 */
    public static Singleton getInstance() {
        return SingletonFactory.instance;
    }
    /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
    public Object readResolve() {
        return getInstance();
    }
    public void print() {
        System.out.println("The use of an inner class to maintain the singleton     kkkkkkkkk");
    }
}
----------------------------------------------------------------------
public class Singleton_1 {
    /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
    private static Singleton_1 instance = null;
    /* 私有构造方法,防止被实例化 */
    private Singleton_1() {}
    /* 静态工程方法,创建实例 */
    public static Singleton_1 getInstance() {
        if (instance == null) {
            instance = new Singleton_1();
        }
        return instance;
    }
    /* 对getInstance方法加synchronized关键字 */
    public static synchronized Singleton_1 getInstance_2() {
        if (instance == null) {
            instance = new Singleton_1();
        }
        return instance;
    }
    /* synchronized关键字锁住的是这个对象 */
    public static Singleton_1 getInstance_3() {
        if (instance == null) {
            synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton_1();
                }
            }
        }
        return instance;
    }
    /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
    public Object readResolve() {
        return instance;
    }
    public void print() {
        System.out.println("Singleton_1   kkkkkkkkk");
    }
}
----------------------------------------------------------------------
public class Test_mail {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Singleton_1.getInstance().print();
        /** ******************* */
        Singleton_1.getInstance_2().print();
        /** ******************getInstance_3* */
        Singleton_1.getInstance_3().print();
        /** ************* */
        Singleton.getInstance().print();
    }
}

享元

-----------------------------------------------
public class ConnectionPool {
    private Vector<Connection> pool;
    public String url = "jdbc:oracle:thin:@192.168.10.22:1521:medi";
    public String username = Jdbc_until.username;
    public String password = Jdbc_until.password;
    public String driverClassName = "oracle.jdbc.driver.OracleDriver";
    private int poolSize = 100;
    private static ConnectionPool instance = null;
    Connection conn = null;
    private ConnectionPool() {
        pool = new Vector<Connection>(poolSize);
        for (int i = 0; i < poolSize; i++) {
            try {
                Class.forName(driverClassName);
                conn = DriverManager.getConnection(url, username, password);
                pool.add(conn);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /* 返回连接到连接池 */
    public synchronized void release() {
        pool.add(conn);
    }
    /* 返回连接池中的一个数据库连接 */
    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        } else {
            return null;
        }
    }

}
-----------------------------------------------
public class Jdbc_until {
    public static String url = null;
    public static String username = null;
    public static String password = null;
    public static String driverClassName = null;
    static {
        Properties p = new Properties();
        try {
            p.load(Object.class.getClass().getResourceAsStream(
                    "/jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        driverClassName = p.getProperty("jdbc.driverClassName");
        url = p.getProperty("jdbc.url");
        username = p.getProperty("jdbc.username");
        password = p.getProperty("jdbc.password");
System.out.println(driverClassName);
System.out.println(url);
System.out.println(username);
System.out.println(password);
    }
}

桥接

------------------------------------------------------------------
public interface Sourceable {
 void method();
}
------------------------------------------------------------------
public class SourceSub1 implements Sourceable {
    public void method() {
        System.out.println("------------SourceSub1 implements Sourceable {-------------");
    }
}
------------------------------------------------------------------
public class SourceSub2 implements Sourceable {
    public void method() {
        System.out.println("------------SourceSub2 implements Sourceable {-------------");
    }
}
------------------------------------------------------------------
public abstract class Bridge {
    private Sourceable source;
    public void getMethod(){
        source.method();
        }
    public Sourceable getSource() {
        return source;
    }
    
    public void setSource(Sourceable source) {
        this.source = source;
    }
}
------------------------------------------------------------------
public class MyBridge extends Bridge {
    public void method(){
        //getMethod();
        
        /*******************************/
        //getSource().method();
    }
}
------------------------------------------------------------------
public class Test_Bridge {
    public static void main(String[] args) {
        MyBridge myBridge=new MyBridge();
        myBridge.setSource(new SourceSub1());
        //myBridge.method();
        myBridge.getMethod();
        /***************************************************/
        myBridge.setSource(new SourceSub2());
        //myBridge.method();
        myBridge.getMethod();        
    }
}

组合

public class TreeNode {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public TreeNode(String name) {
        super();
        this.name = name;
    }
    /************************************/
    private TreeNode parent;
    public TreeNode getParent() {
        return parent;
    }
    public void setParent(TreeNode parent) {
        this.parent = parent;
    }
    /***************************************/
    private Vector<TreeNode> children=new Vector<TreeNode>();
    // add    children node
    public void add(TreeNode note){
        children.add(note);
    }
    // delete children node
    public void remove(TreeNode note){
        children.remove(note);
    }
    // get    children node
    public Enumeration<TreeNode> getChildren(){
        return children.elements();
    }    
}
------------------------------------------
public class Tree {
    public TreeNode root = null;
    public Tree(String name) {
        root = new TreeNode(name);
    }
    public static void main(String[] args) {
        Tree a = new Tree("A");
        TreeNode b = new TreeNode("B");
        TreeNode c = new TreeNode("C");
        b.add(c);
        a.root.add(b);
    }
}

装饰器

----------------------------------------------------------------------------------
public interface Sourceable {
    void method();
}
----------------------------------------------------------------------------------
public class Source implements Sourceable {
    public void method() {
        System.out.println("-----------Source implements Sourceable {------------");
    }
}
----------------------------------------------------------------------------------
public class Decorator implements Sourceable {
    private Source source;
    public void method() {
        System.out.println("---------befor-----source.method();--------");
        source.method();
        System.out.println("---------after-----source.method();-------------");
    }
    public Decorator(Source source) {
        super();
        this.source = source;
    }
}
----------------------------------------------------------------------------------
public class Test_Decorator {
    /**
     * @param args
     */
    public static void main(String[] args) {
        new Source().method();
        /** ****************** */
        new Decorator(new Source()).method();
    }
}

适配器

-------------------------------------------------------------------------------
public class Source {
    public void method1(){
        System.out.println("-----------Source.method1()-----------");
    }
}
-------------------------------------------------------------------------------
public interface Targetable {
     /* 与原类中的方法相同 */  
    public void method1();    
    /* 新类的方法 */  
    public void method2();  
}
-------------------------------------------------------------------------------
public class Wrapper implements Targetable {
    private Source source;
    public Wrapper(Source source) {
        super();
        this.source = source;
    }
    public void method1() {
        source.method1();
    }
    public void method2() {
        System.out.println("------------Wrapper.method2()-----------------");
    }
}

-------------------------------------------------------------------------------
public class Adapter extends Source implements Targetable {
	public void method2() {
		System.out.println("-------------Adapter.method2()-------------");		
	}
}

-------------------------------------------------------------------------------
public abstract class Wrapper2 implements Targetable {
    /* 与原类中的方法相同 */
    public void method1() {};
    /* 新类的方法 */
    public void method2() {};
}
-------------------------------------------------------------------------------
public class SourceSub1 extends Wrapper2 {
    public void method1() {
        System.out.println("the sourceable interface's first Sub1!");  
    };
}
-------------------------------------------------------------------------------
public class SourceSub2 extends Wrapper2 {
	public void method2() {
		System.out.println("the sourceable interface's second Sub2!");  
	};
}

-------------------------------------------------------------------------------
public class Test_Adapter {
	public static void main(String[] args) {
		Adapter adapter=new Adapter();
		adapter.method1();
		adapter.method2();
		/***************************/
		Wrapper wrapper=new Wrapper(new Source());
		wrapper.method1();
		wrapper.method2();
		/******************************/		
		new SourceSub1().method1();
		new SourceSub2().method2();		
	}
}
-------------------------------------------------------------------------------


外观

-------------------------------------------------------------
public class CPU {
    public void startup(){
        System.out.println("------CPU.startup()----------");
    }
    public void shutdown(){
        System.out.println("------CPU.shutdown()----------");
    }
}
-------------------------------------------------------------
public class Disk {
    public void startup(){
        System.out.println("------Disk.startup()----------");
    }
    public void shutdown(){
        System.out.println("------Disk.shutdown()----------");
    }
}
-------------------------------------------------------------
public class Memory {
    public void startup(){
        System.out.println("------Memory.startup()----------");
    }
    public void shutdown(){
        System.out.println("------Memory.shutdown()----------");
    }
}
-------------------------------------------------------------
public class Computer {
	private CPU cpu;  
    private Memory memory;  
    private Disk disk;  
	public Computer() {
		super();
		this.cpu = new CPU();
		this.memory = new Memory();
		this.disk = new Disk();
	}
	public void startup(){
		cpu.startup();
		memory.startup();
		disk.startup();
	}
    public void shutdown(){
    	cpu.shutdown();
		memory.shutdown();
		disk.shutdown();
	} 
    public static void main(String[] args) {
    	Computer c=new  Computer();
    	c.startup();
    	c.shutdown();
	}   
}

代理

------------------------------------------------------------------------------
public interface Sourceable {
    void method();
}
------------------------------------------------------------------------------
public class Source implements Sourceable {
    public void method() {
        System.out.println("----------Source implements Sourceable {-------------");
    }
}
------------------------------------------------------------------------------
public class Proxy implements Sourceable {
	private Source source;
	public Proxy() {
		super();
		this.source = new Source();
	}
	public void method() {
		System.out.println("-------befor----Proxy implements Sourceable {-------");
		source.method();
		System.out.println("-------after----Proxy implements Sourceable {-------");
	}
}
------------------------------------------------------------------------------
public class Test_proxy {
	public static void main(String[] args) {
		Proxy proxy = new Proxy();
		proxy.method();
	}
}

过滤


命令command

------------------------------------------------------------------------
public class Receiver {
    public void action() {
        System.out.println("command received!");
    }
}
------------------------------------------------------------------------
public interface Command {
	void exe();
}
------------------------------------------------------------------------
public class MyCommand implements Command {
    private Receiver receiver;
    public MyCommand(Receiver receiver) {
        super();
        this.receiver = receiver;
    }
    public void exe() {
        receiver.action();
    }
}
------------------------------------------------------------------------
public class Invoker {
	private Command command;
	public Invoker(Command command) {
		super();
		this.command = command;
	}
	public void action() {
		command.exe();
	}
}
------------------------------------------------------------------------
public class Test_Command {
	public static void main(String[] args) {
		Receiver receiver = new Receiver();
		Command command = new MyCommand(receiver);
		Invoker invoker = new Invoker(command);
		invoker.action();
	}
}

责任链chain

----------------------------------------------------------
public interface Handler {
    void operator();
}
----------------------------------------------------------
public abstract class AbstractHandler {
	private Handler handler;
	public Handler getHandler() {
		return handler;
	}
	public void setHandler(Handler handler) {
		this.handler = handler;
	}
}
----------------------------------------------------------
public class MyHandler extends AbstractHandler implements Handler {
	public String name;
	public MyHandler(String name) {
		super();
		this.name = name;
	}
	public void operator() {
		System.out.println("MyHandler=" + name);
		if (getHandler() != null) {
			getHandler().operator();
		}
	}
}
----------------------------------------------------------
public class Test_handler {
	public static void main(String[] args) {
		MyHandler a = new MyHandler("A");
		MyHandler b = new MyHandler("b");
		MyHandler c = new MyHandler("c");
		MyHandler d = new MyHandler("d");
		a.setHandler(b);
		b.setHandler(c);
		c.setHandler(d);
		a.operator();
	}
}

解释器interpreter

-----------------------------------------------------------------
public class Context {
	private int num1;
	private int num2;
	public Context(int num1, int num2) {
		this.num1 = num1;
		this.num2 = num2;
	}
    g/s...
}
-----------------------------------------------------------------
public interface Expression {
	public int interpret(Context context);
}
-----------------------------------------------------------------
public class Minus implements Expression {
	@Override
	public int interpret(Context context) {
		return context.getNum1() - context.getNum2();
	}
}
-----------------------------------------------------------------
public class Plus implements Expression {
	@Override
	public int interpret(Context context) {
		return context.getNum1() + context.getNum2();
	}
}
-----------------------------------------------------------------
public class Test_interpreter {
	public static void main(String[] args) {
		// 计算9+2-8的值
		/*
		 * int result = new Minus().interpret((new Context(new Plus()
		 * .interpret(new Context(9, 2)), 8))); System.out.println(result);
		 */
		Context context = new Context(9, 2);
		System.out.println(new Plus().interpret(context));
		System.out.println(new Minus().interpret(context));

	}
}

迭代子iterator

-------------------------------------------------------
public interface Iterator {
    // 前移
    public Object previous();
    // 后移
    public Object next();
    public boolean hasNext();
    // 取得第一个元素
    public Object first();
}
-------------------------------------------------------
public interface Collection {
	public Iterator iterator();
	/* 取得集合元素 */
	public Object get(int i);
	/* 取得集合大小 */
	public int size();
}
-------------------------------------------------------
public class MyCollection implements Collection {
	public String string[] = { "A", "B", "C", "D", "E" };
	public MyCollection() {
		super();
	}
	public Object get(int i) {
		return string[i];
	}
	public Iterator iterator() {
		return new MyIterator(this);
	}
	public int size() {
		return string.length;
	}
}
-------------------------------------------------------
public class MyIterator implements Iterator {
	private Collection collection;
	private int pos = -1;
	public MyIterator(Collection collection) {
		this.collection = collection;
	}
	public Object first() {
		return collection.get(0);
	}
	public boolean hasNext() {
		if (pos < collection.size() - 1) {
			return true;
		} else {
			return false;
		}
	}
	public Object next() {
		if (pos < collection.size() - 1) {
			pos++;
		}
		return collection.get(pos);
	}
	public Object previous() {
		if (pos > 0) {
			pos--;
		}
		return collection.get(pos);
	}
}
-------------------------------------------------------
public class Test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Collection collection = new MyCollection();
		Iterator it = collection.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

中介者mediator

--------------------------------------------------------------
public interface Mediator {
    public void createMediator();
    public void workAll();
}
--------------------------------------------------------------
public class MyMediator implements Mediator {
    private User user1;
    private User user2;
    public User getUser1() {
        return user1;
    }
    public User getUser2() {
        return user2;
    }
    public void createMediator() {
        user1 = new User1(this);
        user2 = new User2(this);
    }
    public void workAll() {
        user1.work();
        user2.work();
    }
}
--------------------------------------------------------------
public abstract class User {
    private Mediator mediator;
    public Mediator getMediator() {
        return mediator;
    }
    public User(Mediator mediator) {
        this.mediator = mediator;
    }
    public abstract void work();
}
--------------------------------------------------------------
public class User1 extends User {
    public User1(Mediator mediator) {
        super(mediator);
    }
    @Override
    public void work() {
        System.out.println("user1 exe!");
    }
}
--------------------------------------------------------------
public class User2 extends User {
    public User2(Mediator mediator) {
        super(mediator);
    }
    @Override
    public void work() {
        System.out.println("user2 exe!");
    }
}
--------------------------------------------------------------
public class Test_Mediator {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Mediator mediator = new MyMediator();  
        mediator.createMediator();  
        mediator.workAll();  
	}
}

观察者observer

--------------------------------------------------------------------------
public interface Subject {
    /* 增加观察者 */
    public void add(Observer observer);
    /* 删除观察者 */
    public void del(Observer observer);
    /* 通知所有的观察者 */
    public void notifyObservers();
    /* 自身的操作 */
    public void operation();
}
--------------------------------------------------------------------------
public abstract class AbstractSubject implements Subject {
	private Vector<Observer> vector = new Vector<Observer>();
	public void add(Observer observer) {
		vector.add(observer);
	}
	public void del(Observer observer) {
		vector.remove(observer);
	}
	public void notifyObservers() {
		for (Enumeration<Observer> e = vector.elements(); e.hasMoreElements();) {
			e.nextElement().update();
		}
	}
}
--------------------------------------------------------------------------
public class MySubject extends AbstractSubject {
    public void operation() {
        System.out.println("-----------------------------MySubject.operation()-- extends AbstractSubject {");
        notifyObservers();
    }
}
--------------------------------------------------------------------------
public interface Observer {
    void update();
}
--------------------------------------------------------------------------
public class Observer1 implements Observer {
    public void update() {
        System.out.println("-----------Observer1 implements Observer {------------");
    }
}
--------------------------------------------------------------------------
public class Observer2 implements Observer {
    public void update() {
        System.out.println("-----------Observer2 implements Observer {------------");
    }
}
-------------------------------------------------------------------------
public class Test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Subject sub = new MySubject();
		sub.add(new Observer1());
		sub.add(new Observer2());
		sub.operation();
	}
}

备忘录memento

public class Memento {
	private String value;
	public String getValue() {
		return value;
	}
	public Memento(String value) {
		super();
		this.value = value;
	}
	public void setValue(String value) {
		this.value = value;
	} 
}
------------------------------------------------------------------
public class Original {
	private String value;
	public Original(String value) {
		super();
		this.value = value;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public Memento createMemento() {
		return new Memento(value);
	}
	public void restoreMemento(Memento memento) {
		this.value = memento.getValue();
	}
}
------------------------------------------------------------------
public class Storage {
	private Memento memento;
	public Memento getMemento() {
		return memento;
	}
	public Storage(Memento memento) {
		super();
		this.memento = memento;
	}
	public void setMemento(Memento memento) {
		this.memento = memento;
	}	
}
------------------------------------------------------------------
public class Test_memento {
	public static void main(String[] args) {
		Original ori = new Original("ogg");
		Storage stor = new Storage(ori.createMemento());
		System.out.println("---------begin---------");
		// 修改原始类的状态
		System.out.println("init : " + ori.getValue());
		ori.setValue("niu");
		System.out.println("update after : " + ori.getValue());
		// 回复原始类的状态
		ori.restoreMemento(stor.getMemento());
		System.out.println("restoreMemento : " + ori.getValue());
	}
}

模板方法template

-------------------------------------------------------------------
public abstract class AbstractCalculato {
	/* 主方法,实现对本类其它方法的调用 */
	public final int calculate(String exp, String opt) {
		int array[] = split(exp, opt);
		return calculate(array[0], array[1]);
	}
	/* 被子类重写的方法 */
	abstract public int calculate(int num1, int num2);
	public int[] split(String exp, String opt) {
		String array[] = exp.split(opt);
		int arrayInt[] = new int[2];
		arrayInt[0] = Integer.parseInt(array[0]);
		arrayInt[1] = Integer.parseInt(array[1]);
		return arrayInt;
	}
}
-------------------------------------------------------------------
public class Minus extends AbstractCalculato {
	@Override
	public int calculate(int num1, int num2) {
		return num1 - num2;
	}
}
-------------------------------------------------------------------
public class Multiply extends AbstractCalculato {
	@Override
	public int calculate(int num1, int num2) {
		return num1 * num2;
	}
}
-------------------------------------------------------------------
public class Plus extends AbstractCalculato {
	@Override
	public int calculate(int num1, int num2) {
		return num1 + num2;
	}
}
-------------------------------------------------------------------
public class Test_Template_Method {
	public static void main(String[] args) {
		AbstractCalculato p = new Plus();
		String exp="10+6";
		int result=p.calculate(exp, "\\+");
		System.out.println("result1="+result);
		/** *********************** */
		exp="10-6";
		p = new Minus();
		result=p.calculate(exp, "\\-");
		System.out.println("result2="+result);
		/** *********************** */
		exp="10*6";
		p = new Multiply();
		result=p.calculate(exp, "\\*");
		System.out.println("result3="+result);
	}
}

访问者visitor

-------------------------------------------------------------------
public interface Subject {
    public void accept(Visitor visitor);
    public String getSubject();
}
-------------------------------------------------------------------
public class MySubject implements Subject {
	public void accept(Visitor visitor) {
		visitor.visit(this);
	}
	public String getSubject() {
		return "love";
	}
}
-------------------------------------------------------------------
public interface Visitor {
     public void visit(Subject sub); 
}
-------------------------------------------------------------------
public class MyVisitor implements Visitor {
	public void visit(Subject sub) {
		System.out.println("visit the subject:" + sub.getSubject());
	}
}
-------------------------------------------------------------------
public class Test_Visitor {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Visitor visitor = new MyVisitor();
		Subject sub = new MySubject();
		sub.accept(visitor);
	}
}

状态state

------------------------------------------------------------
public class State {
    private String value;
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public void method1() {
        System.out.println("execute the first opt!");
    }
    public void method2() {
        System.out.println("execute the second opt!");
    }
}
------------------------------------------------------------
public class Context {
	private State state;
	public Context(State state) {
		this.state = state;
	}
	public State getState() {
		return state;
	}
	public void setState(State state) {
		this.state = state;
	}
	public void method() {
		if (state.getValue().equals("state1")) {
			state.method1();
		} else if (state.getValue().equals("state2")) {
			state.method2();
		}
	}
}
------------------------------------------------------------
public class Test_State {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		State state = new State();
		Context context = new Context(state);
		// 设置第一种状态
		state.setValue("state1");
		context.method();
		// 设置第二种状态
		state.setValue("state2");
		context.method();
	}
}

策略strategy

-------------------------------------------------------------
public interface ICalculator {
    int calculate(String exp);
}
-------------------------------------------------------------
public abstract class AbstractCalculator {
	public int[] split(String exp, String opt) {
		String array[] = exp.split(opt);
		int arrayInt[] = new int[2];
		arrayInt[0] = Integer.parseInt(array[0]);
		arrayInt[1] = Integer.parseInt(array[1]);
		return arrayInt;
	}
}
-------------------------------------------------------------
public class Minus extends AbstractCalculator implements ICalculator {
	public int calculate(String exp) {
		int arrayInt[] = split(exp, "\\+");
		return arrayInt[0] - arrayInt[1];
	}
}
-------------------------------------------------------------
public class Multiply extends AbstractCalculator implements ICalculator {
	public int calculate(String exp) {
		int arrayInt[] = split(exp, "\\+");
		return arrayInt[0] * arrayInt[1];
	}
}
-------------------------------------------------------------
public class Plus extends AbstractCalculator implements ICalculator {
	public int calculate(String exp) {
		int arrayInt[] = split(exp, "\\+");
		return arrayInt[0] + arrayInt[1];
	}
}
-------------------------------------------------------------
public class Test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String exp = "8+2";
		ICalculator cal = new Plus();
		int result = cal.calculate(exp);
		System.out.println(result);
		/** **************** */
		cal = new Minus();
		result = cal.calculate(exp);
		System.out.println(result);
		/** **************** */
		cal = new Multiply();
		result = cal.calculate(exp);
		System.out.println(result);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值