多态和策略模式有着一些相同之处,这点我主要从概念上面来理解。
多态:相同类型的变量,调用同一个方法时呈现出多种不同的行为特征,主要是通过继承来实现,将子类对象直接赋给父类引用变量,这样在编译时引用变量类型是父类类型,而运行时类型是子类类型,导致运行时调用该引用变量的方法总会表现子类方法,而调用其引用变量的属性则会表现出父类属性。
策略模式:定义了实现,用接口来封装起来,通过构造器的构造参数不同使得实现有所不同。
多态代码:
package test.testforpolymorphism;
public class BaseClass {
public int book = 6;
public void base()
{
System.out.println("superclass basic mothen");
}
public void test()
{
System.out.println("superclass overrided mothen");
}
}
package test.testforpolymorphism;
public class SubClass extends BaseClass {
public String book = "JavaEE";
public void test()
{
System.out.println("subclass override father's mothen");
}
public void sub()
{
System.out.println("subclass original mothen");
}
}
package test.testforpolymorphism;
public class TestForPolymorphism {
public static void main(String[] args)
{
BaseClass bc = new BaseClass();
System.out.println(bc.book);
bc.base();
bc.test();
SubClass sc = new SubClass();
System.out.println(sc.book);
sc.base();
sc.test();
BaseClass ploymophicBc = new SubClass();
System.out.println(ploymophicBc.book);
ploymophicBc.base();
ploymophicBc.test();
}
}
策略代码:
package test.testforstratagy;
public class Salesman {
public static void main(String[] args) {
Context context;
System.out.println("you are a silly man");
context = new Context(new CheatYou());
context.SalesmanBehavior();
System.out.println("you are a smart man");
context = new Context(new HonorYou());
context.SalesmanBehavior();
}
}
package test.testforstratagy;
public interface IStratagy {
public void operate();
}
package test.testforstratagy;
public class Context {
IStratagy iStratagy;
public Context(IStratagy iStratagy)
{
this.iStratagy = iStratagy;
}
public void SalesmanBehavior()
{
iStratagy.operate();
}
}
package test.testforstratagy;
public class CheatYou implements IStratagy {
public void operate()
{
System.out.println("cheat you");
}
}
package test.testforstratagy;
public class HonorYou implements IStratagy{
public void operate()
{
System.out.println("Honor you");
}
}
总体来讲,二者的思想和目的是基本一致的。