Sunday, May 17, 2015

命令模式Command pattern

由wiki里面的定义,命令模式是把action封装起来,方便重复使用。

下面演示一个测试android app基于UiAutomator的程序
1. EventInput: 首先定义event/command的输入参数
2. Events: 一系列的actions
3. Operator: 对应不同的input,invoke相应的action
4. Main class: 列出所有input, 然后operator开始做事

public abstract class EventInput {
public EventInput followingInput;
}

import java.util.ArrayList;
public class ClickEventInput extends EventInput{

protected String target;

//for GetListValues
public ClickEventInput(){}
public ClickEventInput(EventInput followingInput)
{
this.followingInput = followingInput;
}

public ClickEventInput(String target)
{
this(target,null);
}

public ClickEventInput(String target, EventInput followingInput)
{
this.target = target;
this.followingInput = followingInput;
}

}

public class Events {
       protected static Operator op;

protected Events(Operator op)
{
this.op = op;
}

public void Click(UiDevice device, String buttonName, EventInput followingInput) throws UiObjectNotFoundException
{
try
{
 if(new UiObject(new UiSelector().text(buttonName)).exists())
new UiObject(new UiSelector().text(buttonName)).clickAndWaitForNewWindow();

}
    catch(Exception e)
    {
    Util.Log(3, "Can't press button", buttonName+","+e.toString());
    return;
    }

if(followingInput!=null)
  op.InvokeAction(followingInput);
}
}


如果有其他行为,写custom类覆盖
public class CarEvents extends Events{

public CarEvents(Operator op) {
super(op);
}

public void Click(UiDevice device, String buttonName, EventInput followingInput) throws UiObjectNotFoundException
       {
        }
}


public class Operator{

UiDevice device;
EventInput input;

        public void InvokeAction(EventInput input)
{
Class cls = null;
Object value = false;

            Class[] constructorArg = new Class[1];
            constructorArg[0] = Operator.class;
            Object obj = cls.getDeclaredConstructor(constructorArg).newInstance(this);

            if(input instanceof ClickEventInput)
            {
            Method method = null;
                Class[] cArg = new Class[3];
                cArg[0] = UiDevice.class;
                cArg[1] = String.class;
                cArg[2] = EventInput.class;
                
                ClickEventInput cInput = (ClickEventInput)input;
                method = cls.getMethod("Click",cArg);
                method.invoke(obj,device,cInput.target, input.followingInput);
            }

}
}

public class NewCar extends UiAutomatorTestCase {   

public void testDemo() throws UiObjectNotFoundException {   

             EventInput input = new ClickEventInput("MAKE & MODEL",,new SleepEventInput(3));
             Operator op = new Operator(getUiDevice(), input,"Car", CarEvents.class);
             op.Start();
        }
}
        

No comments:

Post a Comment