题目:商场做活动,有三种:正常收费、满300返100、打8折
效果图:
下面是策略和工厂结合
public abstract class Strategy { public abstract double acceptCash(double money); }
public class StrategyNormal extends Strategy { @Override public double acceptCash(double money) { return money; } } public class StrategyReturn extends Strategy { private double moneyCondition; private double moneyReturn; public StrategyReturn(String moneyCondition, String moneyReturn) { this.moneyCondition = Double.parseDouble(moneyCondition); this.moneyReturn = Double.parseDouble(moneyReturn); } @Override public double acceptCash(double money) { double result = 0; if (money >= moneyCondition) { result = money - Math.floor(money / moneyCondition) * moneyReturn; } return result; } } public class StrategySale extends Strategy { private double sale; public StrategySale(String sale) { this.sale = Double.parseDouble(sale); } @Override public double acceptCash(double money) { return money * sale; } }
public class ContextStrategy { private Strategy strategy; public ContextStrategy(String type) { switch (type) { case "正常收费": strategy = new StrategyNormal(); break; case "满300返100": strategy = new StrategyReturn("300", "100"); break; case "打8折": strategy = new StrategySale("0.8"); break; } } public double contextImpl(double money) { double result = 0; if (null != strategy) { result = strategy.acceptCash(money); } return result; } }
public class StrategyActivity extends AppCompatActivity { private Spinner spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_strategy); spinner = (Spinner) findViewById(R.id.spinner); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView textView = (TextView) view; ContextStrategy contextStrategy = new ContextStrategy(textView.getText().toString()); Toast.makeText(StrategyActivity.this, contextStrategy.contextImpl(1000) + "", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } }
布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.administrator.schema1.StrategyFactory.StrategyActivity"> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:entries="@array/spinner"></Spinner> </RelativeLayout>
arrays.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="spinner"> <item>正常收费</item> <item>满300返100</item> <item>打8折</item> </string-array> </resources>
ContextStrategy是策略类,它创建对象且调用策略,判断条件不要写在StartegyActivity(客户端)
简单工厂模式和策略模式的区别:
简单工厂模式通过多态能得到抽象父类,它注重的是对象;而策略模式不关心对象,策略类封装了方法,直接调用就可以了。