zoukankan      html  css  js  c++  java
  • Active Objects模式

    实现的思路是,通过代理将方法的调用转变为向阻塞队列中添加一个请求,由一个线程取出请求后执行实际的方法,然后将结果设置到Future中

    这里用到了代理模式,Future模式

    /**************************************
     * 接受异步消息的主动对象
     * 
     **/
    public interface ActiveObject {
    
        Result makeString(int count,char fillChar);
    
        void displayString(String text);
    }
    /*
     * 主动对象的实现类
     * 
     */
    class Servant implements ActiveObject {
    
        @Override
        public Result makeString(int count, char fillChar) {
            char[] buf = new char[count];
            for (int i = 0; i < count; i++) {
                buf[i] = fillChar;
            }
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
    
            }
            return new RealResult(new String(buf));
        }
    
        @Override
        public void displayString(String text) {
            try {
                Thread.sleep(2000);
                System.out.println("Display:" + text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 主动对象的代理类
     *
     */
    class ActiveObjectProxy implements ActiveObject {
    
        private final SchedulerThread schedulerThread;
    
        private final Servant servant;
    
        public ActiveObjectProxy(SchedulerThread schedulerThread, Servant servant) {
            this.schedulerThread = schedulerThread;
            this.servant = servant;
        }
    
        @Override
        public Result makeString(int count, char fillChar) {
            FutureResult future = new FutureResult();
            //往队列里添加调用请求MethodRequest
            schedulerThread.invoke(new MakeStringRequest(servant, future, count, fillChar));
            return future;
        }
    
        @Override
        public void displayString(String text) {
            schedulerThread.invoke(new DisplayStringRequest(servant, text));
        }
    }
    /**
     * 工具类
     */
    public final class ActiveObjectFactory {
    
        private ActiveObjectFactory() {
        }
    
        public static ActiveObject createActiveObject() {
            Servant servant = new Servant();
            ActivationQueue queue = new ActivationQueue();
            SchedulerThread schedulerThread = new SchedulerThread(queue);
            ActiveObjectProxy proxy = new ActiveObjectProxy(schedulerThread,servant);
            schedulerThread.start();
            return proxy;
        }
    }
    /**
     * 
     *  调度者,从队列里取出任务并执行
     *  
     */
    public class SchedulerThread extends Thread {
    
        private final ActivationQueue activationQueue;
    
        public SchedulerThread(ActivationQueue  activationQueue) {
            this.activationQueue = activationQueue;
        }
    
        public void invoke(MethodRequest request) {
            this.activationQueue.put(request);
        }
    
        @Override
        public void run() {
            while (true) {
                activationQueue.take().execute();
            }
        }
    }
    /***
     * 阻塞队列
     */
    public class ActivationQueue {
    
        private final static int DEFAULT_SIZE = 100;
    
        private final LinkedList<MethodRequest> methodQueue;
    
        public ActivationQueue() {
            methodQueue = new LinkedList<>();
        }
    
        public synchronized void put(MethodRequest request) {
            while (methodQueue.size() >= DEFAULT_SIZE) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.methodQueue.addLast(request);
            this.notifyAll();
        }
    
        public synchronized MethodRequest take() {
            while (methodQueue.isEmpty()) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            MethodRequest methodRequest = methodQueue.removeFirst();
            this.notifyAll();
            return methodRequest;
        }
    }
    /**
     * 返回结果
     *
     */
    public interface Result {
    
        Object getResultValue();
    
    }
    /**
     * 返回的对象
     */
    public class RealResult implements Result {
    
        private final Object resultValue;
    
        public RealResult(Object resultValue) {
            this.resultValue = resultValue;
        }
    
        @Override
        public Object getResultValue() {
            return this.resultValue;
        }
    }
    /**
     * 
     * 实际返回给客户的result
     *
     */
    public class FutureResult implements Result {
    
        private Result result;
    
        private boolean ready = false;
    
        public synchronized void setResult(Result result) {
            this.result = result;
            this.ready = true;
            this.notifyAll();
        }
    
        @Override
        public synchronized Object getResultValue() {
            while (!ready) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return this.result.getResultValue();
        }
    }
    /**
     * 调用请求
     */
    public abstract class MethodRequest {
    
        protected final Servant servant;
    
        protected final FutureResult futureResult;
    
        public MethodRequest(Servant servant, FutureResult futureResult) {
            this.servant = servant;
            this.futureResult = futureResult;
        }
    
        public abstract void execute();
    }
    /**
     * 
     *  拼接字符
     */
    public class MakeStringRequest extends MethodRequest {
    
        private final int count;
        private final char fillChar;
    
        public MakeStringRequest(Servant servant, FutureResult futureResult, int count, char fillChar) {
            super(servant, futureResult);
            this.fillChar = fillChar;
            this.count = count;
        }
    
        @Override
        public void execute() {
            Result result = servant.makeString(count, fillChar);
            futureResult.setResult(result);
        }
    }
    /**
     * 打印字符串
     *
     */
    public class DisplayStringRequest extends MethodRequest {
    
        private final String text;
    
        public DisplayStringRequest(Servant servant, final String text) {
            super(servant, null);
            this.text = text;
        }
    
        @Override
        public void execute() {
            this.servant.displayString(text);
        }
    }
    public class Test {
    
        public static void main(String[] args) {
    
            ActiveObject activeObject = ActiveObjectFactory.createActiveObject();
            activeObject.displayString("VVVVVVVVVV");
            Result makeString = activeObject.makeString(7, 'A');
            System.out.println("#################");
            System.out.println(makeString.getResultValue());
            
        }
    }
  • 相关阅读:
    hdoj2187:悼念512汶川大地震遇难同胞 (贪心)
    2.0其它之Transform详解,以及UIElement和FrameworkElement的常用属性
    2.0外观之样式, 模板, 视觉状态和视觉状态管理器
    2.0图形之Ellipse, Line, Path, Polygon, Polyline, Rectangle
    2.0控件之ListBox, MediaElement, MultiScaleImage, PasswordBox, ProgressBar, RadioButton
    2.0画笔之SolidColorBrush, ImageBrush, VideoBrush, LinearGradientBrush, RadialGradientBrush
    2.0图形之基类System.Windows.Shapes.Shape
    2.0交互之鼠标事件和键盘事件
    2.0控件之ScrollViewer, Slider, StackPanel, TabControl, TextBlock, TextBox, ToggleButton
    2.0交互之InkPresenter(涂鸦板)
  • 原文地址:https://www.cnblogs.com/moris5013/p/10919502.html
Copyright © 2011-2022 走看看