No enclosing instance of type StrategyTest(内部类) is accessible. Must qualify the allocation with an e

No enclosing instance of type StrategyTest is accessible. Must qualify the allocation with an enclosing instance of type StrategyTest (e.g. x.new A() where x is an instance of StrategyTest).

翻译过来:无法访问StrategyTest类型的封闭实例。必须使用StrategyTest类型的封闭实例限定分配(例如x.new A(),其中x是战略测试)。
注:其中StrategyTest是内部类

我明明已经创建了一个实例 为什么还会显示我没有实例呢

之后才发现 原来主程序是主程序是public static void main(String[] args)

因为创建类时public class 没有加static 则该类成为了动态类

类的定义:类中的静态方法不能直接调用动态方法 因此报错

修改方法 最直接的是在创建类时 加上静态 static 如下:

下面展示的是我 单例模式的例子。

//创建一个策略实体类
public class StrategyTest {
    //创建一个接口
	public interface Strategy {
		   public int operation(int num1, int num2);
		}
    
	public static class Operation implements Strategy{
		   @Override
		   public int operationOne(int num1, int num2) {
		      return num1 + num2;
		   }
		}
	public static class OperationSubtract implements Strategy{
		   @Override
		   public int operationTwo(int num1, int num2) {
		      return num1 - num2;
		   }
		}
	public static class Context {
		   private Strategy strategy;
		 
		   public Context(Strategy strategy){
		      this.strategy = strategy;
		   }
		 
		   public int executeStrategy(int num1, int num2){
		      return strategy.operation(num1, num2);
		   }
		}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		 Context context = new Context(new OperationOne());    
	      System.out.println("2 + 1 = " + context.executeStrategy(2, 1));
	 
	      context = new Context(new OperationTwo());      
	      System.out.println("2 - 1 = " + context.executeStrategy(2, 1));
	}

}

在这里插入图片描述

策略模式代码部分参考:链接: https://www.runoob.com/design-pattern/strategy-pattern.html.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值