设计模式(Design Patterns) —&mda ...
设计模式(Design Patterns)
——可复用面向对象软件的基础
设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的,设计模式使代码编制真正工程化,设计模式是软件工程的基石,如同大厦的一块块砖石一样。项目中合理的运用设计模式可以完美的解决很多问题,每种模式在现在中都有相应的原理来与之对应,每一个模式描述了一个在我们周围不断重复发生的问题,以及该问题的核心解决方案,这也是它能被广泛应用的原因。本章系Java之美[从菜鸟到高手演变]系列之设计模式,我们会以理论与实践相结合的方式来进行本章的学习,希望广大程序爱好者,学好设计模式,做一个优秀的软件工程师!
企业级项目实战(带源码)地址:http://zz563143188.iteye.com/blog/1825168
23种模式java实现源码下载地址 http://pan.baidu.com/share/link?shareid=372668&uk=4076915866#dir/path=%2F%E5%AD%A6%E4%B9%A0%E6%96%87%E4%BB%B6
- public interface Sender {
- public void Send();
- }
- public class MailSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is mailsender!");
- }
- }
- public class SmsSender implements Sender {
-
- @Override
- public void Send() {
- System.out.println("this is sms sender!");
- }
- }
- public class SendFactory {
-
- public Sender produce(String type) {
- if ("mail".equals(type)) {
- return new MailSender();
- } else if ("sms".equals(type)) {
- return new SmsSender();
- } else {
- System.out.println("请输入正确的类型!");
- return null;
- }
- }
- }
- return new MailSender();
- }
-
- public Sender produceSms(){
- return new SmsSender();
- }
- }
- public class FactoryTest {
-
- public static void main(String[] args) {
- SendFactory factory = new SendFactory();
- Sender sender = factory.produceMail();
- sender.Send();
- }
- }
- public class SendFactory {
-
- public static Sender produceMail(){
- return new MailSender();
- }
-
- public static Sender produceSms(){
- return new SmsSender();
- }
- }
- public class FactoryTest {
-
- public static void main(String[] args) {
- Sender sender = SendFactory.produceMail();
- sender.Send();
- }
- }
- public interface Sender {
- public void Send();
- }
- public class MailSender implements Sender {
- @Override
- public void Send() {
- System.out.println("this is mailsender!");
- }
- }
- public class SmsSender implements Sender {
-
- @Override
- public void Send() {
- System.out.println("this is sms sender!");
- }
- }
- public class SendMailFactory implements Provider {
-
- @Override
- public Sender produce(){
- return new MailSender();
- }
- }
- public class SendSmsFactory implements Provider{
-
- @Override
- public Sender produce() {
- return new SmsSender();
- }
- }
- public interface Provider {
- public Sender produce();
- }
- public class Test {
-
- public static void main(String[] args) {
- Provider provider = new SendMailFactory();
- Sender sender = provider.produce();
- sender.Send();
- }
- }
- public class Singleton {
-
- /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
- private static Singleton instance = null;
-
- /* 私有构造方法,防止被实例化 */
- private Singleton() {
- }
-
- /* 静态工程方法,创建实例 */
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
-
- /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
- public Object readResolve() {
- return instance;
- }
- }
- public static synchronized Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- public static Singleton getInstance() {
- if (instance == null) {
- synchronized (instance) {
- if (instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- private static class SingletonFactory{
- private static Singleton instance = new Singleton();
- }
- public static Singleton getInstance(){
- return SingletonFactory.instance;
- }
- 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 class SingletonTest {
-
- private static SingletonTest instance = null;
-
- private SingletonTest() {
- }
-
- private static synchronized void syncInit() {
- if (instance == null) {
- instance = new SingletonTest();
- }
- }
-
- public static SingletonTest getInstance() {
- if (instance == null) {
- syncInit();
- }
- return instance;
- }
- }
- public class SingletonTest {
-
- private static SingletonTest instance = null;
- private Vector properties = null;
-
- public Vector getProperties() {
- return properties;
- }
-
- private SingletonTest() {
- }
-
- private static synchronized void syncInit() {
- if (instance == null) {
- instance = new SingletonTest();
- }
- }
-
- public static SingletonTest getInstance() {
- if (instance == null) {
- syncInit();
- }
- return instance;
- }
-
- public void updateProperties() {
- SingletonTest shadow = new SingletonTest();
- properties = shadow.getProperties();
- }
- }
- public class Builder {
-
- private List<Sender> list = new ArrayList<Sender>();
-
- public void produceMailSender(int count){
- for(int i=0; i<count; i++){
- list.add(new MailSender());
- }
- }
-
- public void produceSmsSender(int count){
- for(int i=0; i<count; i++){
- list.add(new SmsSender());
- }
- }
- }
- public class Test {
-
- public static void main(String[] args) {
- Builder builder = new Builder();
- builder.produceMailSender(10);
- }
- }
- public class Prototype implements Cloneable {
-
- public Object clone() throws CloneNotSupportedException {
- Prototype proto = (Prototype) super.clone();
- return proto;
- }
- }
- 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);
- 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 Source {
-
- public void method1() {
- System.out.println("this is original method!");
- }
- }
- public interface Targetable {
-
- /* 与原类中的方法相同 */
- public void method1();
-
- /* 新类的方法 */
- public void method2();
- }
- public class Adapter extends Source implements Targetable {
-
- @Override
- public void method2() {
- System.out.println("this is the targetable method!");
- }
- }
- public class AdapterTest {
-
- public static void main(String[] args) {
- Targetable target = new Adapter();
- target.method1();
- target.method2();
- }
- }
- public class Wrapper implements Targetable {
-
- private Source source;
-
- public Wrapper(Source source){
- super();
- this.source = source;
- }
- @Override
- public void method2() {
- System.out.println("this is the targetable method!");
- }
-
- @Override
- public void method1() {
- source.method1();
- }
- }
- public class AdapterTest {
-
- public static void main(String[] args) {
- Source source = new Source();
- Targetable target = new Wrapper(source);
- target.method1();
- target.method2();
- }
- }
- public interface Sourceable {
-
- public void method1();
- public void method2();
- }
- public abstract class Wrapper2 implements Sourceable{
-
- 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 WrapperTest {
-
- public static void main(String[] args) {
- Sourceable source1 = new SourceSub1();
- Sourceable source2 = new SourceSub2();
-
- source1.method1();
- source1.method2();
- source2.method1();
- source2.method2();
- }
- }
- public interface Sourceable {
- public void method();
- }
- public class Source implements Sourceable {
-
- @Override
- public void method() {
- System.out.println("the original method!");
- }
- }
- public class Decorator implements Sourceable {
-
- private Sourceable source;
-
- public Decorator(Sourceable source){
- super();
- this.source = source;
- }
- @Override
- public void method() {
- System.out.println("before decorator!");
- source.method();
- System.out.println("after decorator!");
- }
- }
- public class DecoratorTest {
-
- public static void main(String[] args) {
- Sourceable source = new Source();
- Sourceable obj = new Decorator(source);
- obj.method();
- }
- }
- public interface Sourceable {
- public void method();
- }
- public class Source implements Sourceable {
-
- @Override
- public void method() {
- System.out.println("the original method!");
- }
- }
- public class Proxy implements Sourceable {
-
- private Source source;
- public Proxy(){
- super();
- this.source = new Source();
- }
- @Override
- public void method() {
- before();
- source.method();
- atfer();
- }
- private void atfer() {
- System.out.println("after proxy!");
- }
- private void before() {
- System.out.println("before proxy!");
- }
- }
- public class ProxyTest {
-
- public static void main(String[] args) {
- Sourceable source = new Proxy();
- source.method();
- }
-
- }
- public class CPU {
-
- public void startup(){
- System.out.println("cpu startup!");
- }
-
- public void shutdown(){
- System.out.println("cpu shutdown!");
- }
- }
- public class Memory {
-
- public void startup(){
- System.out.println("memory startup!");
- }
-
- public void shutdown(){
- System.out.println("memory shutdown!");
- }
- }
- public class Disk {
-
- public void startup(){
- System.out.println("disk startup!");
- }
-
- public void shutdown(){
- System.out.println("disk shutdown!");
- }
- }
- public class Computer {
- private CPU cpu;
- private Memory memory;
- private Disk disk;
-
- public Computer(){
- cpu = new CPU();
- memory = new Memory();
- disk = new Disk();
- }
-
- public void startup(){
- System.out.println("start the computer!");
- cpu.startup();
- memory.startup();
- disk.startup();
- System.out.println("start computer finished!");
- }
-
- public void shutdown(){
- System.out.println("begin to close the computer!");
- cpu.shutdown();
- memory.shutdown();
- disk.shutdown();
- System.out.println("computer closed!");
- }
- }
- public class User {
-
- public static void main(String[] args) {
- Computer computer = new Computer();
- computer.startup();
- computer.shutdown();
- }
- }
- public interface Sourceable {
- public void method();
- }
- public class SourceSub1 implements Sourceable {
-
- @Override
- public void method() {
- System.out.println("this is the first sub!");
- }
- }
- public class SourceSub2 implements Sourceable {
-
- @Override
- public void method() {
- System.out.println("this is the second sub!");
- }
- }
- public abstract class Bridge {
- private Sourceable source;
-
- public void method(){
- source.method();
- }
-
- public Sourceable getSource() {
- return source;
- }
-
- public void setSource(Sourceable source) {
- this.source = source;
- }
- }
- public class MyBridge extends Bridge {
- public void method(){
- getSource().method();
- }
- }
- public class BridgeTest {
-
- public static void main(String[] args) {
-
- Bridge bridge = new MyBridge();
-
- /*调用第一个对象*/
- Sourceable source1 = new SourceSub1();
- bridge.setSource(source1);
- bridge.method();
-
- /*调用第二个对象*/
- Sourceable source2 = new SourceSub2();
- bridge.setSource(source2);
- bridge.method();
- }
- }
- public class TreeNode {
-
- private String name;
- private TreeNode parent;
- private Vector<TreeNode> children = new Vector<TreeNode>();
-
- public TreeNode(String name){
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public TreeNode getParent() {
- return parent;
- }
-
- public void setParent(TreeNode parent) {
- this.parent = parent;
- }
-
- //添加孩子节点
- public void add(TreeNode node){
- children.add(node);
- }
-
- //删除孩子节点
- public void remove(TreeNode node){
- children.remove(node);
- }
-
- //取得孩子节点
- public Enumeration<TreeNode> getChildren(){
- return children.elements();
- }
- }
- public class Tree {
-
- TreeNode root = null;
-
- public Tree(String name) {
- root = new TreeNode(name);
- }
-
- public static void main(String[] args) {
- Tree tree = new Tree("A");
- TreeNode nodeB = new TreeNode("B");
- TreeNode nodeC = new TreeNode("C");
-
- nodeB.add(nodeC);
- tree.root.add(nodeB);
- System.out.println("build the tree finished!");
- }
- }
- public class ConnectionPool {
-
- private Vector<Connection> pool;
-
- /*公有属性*/
- private String url = "jdbc:mysql://localhost:3306/test";
- private String username = "root";
- private String password = "root";
- private String driverClassName = "com.mysql.jdbc.Driver";
-
- 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;
- }
- }
- }
本章是关于设计模式的最后一讲,会讲到第三种设计模式——行为型模式,共11种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。这段时间一直在写关于设计模式的东西,终于写到一半了,写博文是个很费时间的东西,因为我得为读者负责,不论是图还是代码还是表述,都希望能尽量写清楚,以便读者理解,我想不论是我还是读者,都希望看到高质量的博文出来,从我本人出发,我会一直坚持下去,不断更新,源源动力来自于读者朋友们的不断支持,我会尽自己的努力,写好每一篇文章!希望大家能不断给出意见和建议,共同打造完美的博文!
先来张图,看看这11中模式的关系:
第一类:通过父类与子类的关系进行实现。第二类:两个类之间。第三类:类的状态。第四类:通过中间类
13、策略模式(strategy)
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下:
图中ICalculator提供同意的方法,
- public interface ICalculator {
- public 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 Plus extends AbstractCalculator implements ICalculator {
-
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"\\+");
- return arrayInt[0]+arrayInt[1];
- }
- }
- public class Minus extends AbstractCalculator implements ICalculator {
-
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"-");
- return arrayInt[0]-arrayInt[1];
- }
-
- }
- public class Multiply extends AbstractCalculator implements ICalculator {
-
- @Override
- public int calculate(String exp) {
- int arrayInt[] = split(exp,"\\*");
- return arrayInt[0]*arrayInt[1];
- }
- }
- public class StrategyTest {
-
- public static void main(String[] args) {
- String exp = "2+8";
- ICalculator cal = new Plus();
- int result = cal.calculate(exp);
- System.out.println(result);
- }
- }
- public abstract class AbstractCalculator {
-
- /*主方法,实现对本类其它方法的调用*/
- 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 Plus extends AbstractCalculator {
-
- @Override
- public int calculate(int num1,int num2) {
- return num1 + num2;
- }
- }
- public class StrategyTest {
-
- public static void main(String[] args) {
- String exp = "8+8";
- AbstractCalculator cal = new Plus();
- int result = cal.calculate(exp, "\\+");
- System.out.println(result);
- }
- }
- public interface Observer {
- public void update();
- }
- public class Observer1 implements Observer {
-
- @Override
- public void update() {
- System.out.println("observer1 has received!");
- }
- }
- public class Observer2 implements Observer {
-
- @Override
- public void update() {
- System.out.println("observer2 has received!");
- }
-
- }
- 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>();
- @Override
- public void add(Observer observer) {
- vector.add(observer);
- }
-
- @Override
- public void del(Observer observer) {
- vector.remove(observer);
- }
-
- @Override
- public void notifyObservers() {
- Enumeration<Observer> enumo = vector.elements();
- while(enumo.hasMoreElements()){
- enumo.nextElement().update();
- }
- }
- }
- public class MySubject extends AbstractSubject {
-
- @Override
- public void operation() {
- System.out.println("update self!");
- notifyObservers();
- }
-
- }
- public class ObserverTest {
-
- public static void main(String[] args) {
- Subject sub = new MySubject();
- sub.add(new Observer1());
- sub.add(new Observer2());
-
- sub.operation();
- }
-
- }
- public interface Collection {
-
- public Iterator iterator();
-
- /*取得集合元素*/
- public Object get(int i);
-
- /*取得集合大小*/
- public int size();
- }
- public interface Iterator {
- //前移
- public Object previous();
-
- //后移
- public Object next();
- public boolean hasNext();
-
- //取得第一个元素
- public Object first();
- }
- public class MyCollection implements Collection {
-
- public String string[] = {"A","B","C","D","E"};
- @Override
- public Iterator iterator() {
- return new MyIterator(this);
- }
-
- @Override
- public Object get(int i) {
- return string[i];
- }
-
- @Override
- 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;
- }
-
- @Override
- public Object previous() {
- if(pos > 0){
- pos--;
- }
- return collection.get(pos);
- }
-
- @Override
- public Object next() {
- if(pos<collection.size()-1){
- pos++;
- }
- return collection.get(pos);
- }
-
- @Override
- public boolean hasNext() {
- if(pos<collection.size()-1){
- return true;
- }else{
- return false;
- }
- }
-
- @Override
- public Object first() {
- pos = 0;
- return collection.get(pos);
- }
-
- }
- public class Test {
-
- public static void main(String[] args) {
- Collection collection = new MyCollection();
- Iterator it = collection.iterator();
-
- while(it.hasNext()){
- System.out.println(it.next());
- }
- }
- }
- public interface Handler {
- public 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 {
-
- private String name;
-
- public MyHandler(String name) {
- this.name = name;
- }
-
- @Override
- public void operator() {
- System.out.println(name+"deal!");
- if(getHandler()!=null){
- getHandler().operator();
- }
- }
- }
- public class Test {
-
- public static void main(String[] args) {
- MyHandler h1 = new MyHandler("h1");
- MyHandler h2 = new MyHandler("h2");
- MyHandler h3 = new MyHandler("h3");
-
- h1.setHandler(h2);
- h2.setHandler(h3);
-
- h1.operator();
- }
- }
- public interface Command {
- public void exe();
- }
- public class MyCommand implements Command {
-
- private Receiver receiver;
-
- public MyCommand(Receiver receiver) {
- this.receiver = receiver;
- }
-
- @Override
- public void exe() {
- receiver.action();
- }
- }
- public class Receiver {
- public void action(){
- System.out.println("command received!");
- }
- }
- public class Invoker {
-
- private Command command;
-
- public Invoker(Command command) {
- this.command = command;
- }
-
- public void action(){
- command.exe();
- }
- }
- public class Test {
-
- public static void main(String[] args) {
- Receiver receiver = new Receiver();
- Command cmd = new MyCommand(receiver);
- Invoker invoker = new Invoker(cmd);
- invoker.action();
- }
- }
- public class Original {
-
- private String value;
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
- public Original(String value) {
- this.value = value;
- }
-
- public Memento createMemento(){
- return new Memento(value);
- }
-
- public void restoreMemento(Memento memento){
- this.value = memento.getValue();
- }
- }
- public class Memento {
-
- private String value;
-
- public Memento(String value) {
- this.value = value;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
- }
- public class Storage {
-
- private Memento memento;
-
- public Storage(Memento memento) {
- this.memento = memento;
- }
-
- public Memento getMemento() {
- return memento;
- }
-
- public void setMemento(Memento memento) {
- this.memento = memento;
- }
- }
- public class Test {
-
- public static void main(String[] args) {
-
- // 创建原始类
- Original origi = new Original("egg");
-
- // 创建备忘录
- Storage storage = new Storage(origi.createMemento());
-
- // 修改原始类的状态
- System.out.println("初始化状态为:" + origi.getValue());
- origi.setValue("niu");
- System.out.println("修改后的状态为:" + origi.getValue());
-
- // 回复原始类的状态
- origi.restoreMemento(storage.getMemento());
- System.out.println("恢复后的状态为:" + origi.getValue());
- }
- }
- package com.xtfggef.dp.state;
-
- /**
- * 状态类的核心类
- * 2012-12-1
- * @author erqing
- *
- */
- 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!");
- }
- }
- package com.xtfggef.dp.state;
-
- /**
- * 状态模式的切换类 2012-12-1
- * @author erqing
- *
- */
- 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 {
-
- 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();
- }
- }
- public interface Visitor {
- public void visit(Subject sub);
- }
- public class MyVisitor implements Visitor {
-
- @Override
- public void visit(Subject sub) {
- System.out.println("visit the subject:"+sub.getSubject());
- }
- }
- public interface Subject {
- public void accept(Visitor visitor);
- public String getSubject();
- }
- public class MySubject implements Subject {
-
- @Override
- public void accept(Visitor visitor) {
- visitor.visit(this);
- }
-
- @Override
- public String getSubject() {
- return "love";
- }
- }
- public class Test {
-
- public static void main(String[] args) {
-
- Visitor visitor = new MyVisitor();
- Subject sub = new MySubject();
- sub.accept(visitor);
- }
- }
- 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;
- }
-
- @Override
- public void createMediator() {
- user1 = new User1(this);
- user2 = new User2(this);
- }
-
- @Override
- 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 {
-
- public static void main(String[] args) {
- Mediator mediator = new MyMediator();
- mediator.createMediator();
- mediator.workAll();
- }
- }
- public interface Expression {
- public int interpret(Context context);
- }
- public class Plus implements Expression {
-
- @Override
- public int interpret(Context context) {
- return context.getNum1()+context.getNum2();
- }
- }
- public class Minus implements Expression {
-
- @Override
- public int interpret(Context context) {
- return context.getNum1()-context.getNum2();
- }
- }
- public class Context {
-
- private int num1;
- private int num2;
-
- public Context(int num1, int num2) {
- this.num1 = num1;
- this.num2 = num2;
- }
-
- public int getNum1() {
- return num1;
- }
- public void setNum1(int num1) {
- this.num1 = num1;
- }
- public int getNum2() {
- return num2;
- }
- public void setNum2(int num2) {
- this.num2 = num2;
- }
-
-
- }
- public class Test {
-
- 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);
- }
- }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:Java开发中的23种设计模式(转)
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。