之前博客简单说了一下简单工厂模式,http://blog.youkuaiyun.com/guideit/article/details/52227970。
但是有个不好地方,他的逻辑代码类使用了静态对象针对这个,我对之前代码进行了优化,直接飙代码。
接口:
package com.example.hujhguiyhiu.test_demo.DaHuaMoShi_2; /** * Created by hujhguiyhiu on 2016/8/16. */ public interface FengZhuang2 { //虚方法,主要就是在继承者们那进行逻辑运算 public double yunSuan(double a,Integer b); }
之前这个是一个封装类。但是优化的时候,觉得,数据还是直接传比较方便就修改了。
逻辑类代码:package com.example.hujhguiyhiu.test_demo.DaHuaMoShi_2; import android.util.Log; /** * Created by hujhguiyhiu on 2016/8/16. */ public class YunSuanIpm2 { public final String TYPE_SY = "SY"; public final String TYPE_ZLX = "ZLX"; public final String TYPE_FP = "FP"; FengZhuang2 fz = null; public YunSuanIpm2(String type, double a, Integer b) { switch (type) { case TYPE_FP: fz = new fpYunSua(); fz.yunSuan(a, b); break; case TYPE_SY: fz = new syYunSua(); fz.yunSuan(a, b); break; case TYPE_ZLX: fz = new zlxYunSua(); fz.yunSuan(a, b); break; } } public class syYunSua implements FengZhuang2 { @Override public double yunSuan(double a, Integer b) { Log.d("test", "a=" + a + ",b=" + b); double t = 0; t = a + b; Log.d("test", "sy总计:" + t); return t; } } public class zlxYunSua implements FengZhuang2 { @Override public double yunSuan(double a, Integer b) { Log.d("test", "a=" + a + ",b=" + b); double t = 0; t = a + b; Log.d("test", "zlx总计:" + t); return t; } } public class fpYunSua implements FengZhuang2 { @Override public double yunSuan(double a, Integer b) { Log.d("test", "a=" + a + ",b=" + b); double t = 0; t = a + b; Log.d("test", "fp总计:" + t); return t; } } }这里是重点,构造方法取代了普通方法,并且获取数据,这样一来,就可以去除静态对象了。主函数:package com.example.hujhguiyhiu.test_demo.DaHuaMoShi_2; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.hujhguiyhiu.test_demo.DaHuaMoShi_1.FengZhuang; import com.example.hujhguiyhiu.test_demo.DaHuaMoShi_1.YunSuanIpm; import com.example.hujhguiyhiu.test_demo.R; /** * Created by hujhguiyhiu on 2016/8/16. */ public class DHMS_Activity2 extends AppCompatActivity { private FengZhuang2 fz; private EditText editText1; private EditText editText2; private Button bt1; public final String TYPE_SY = "SY"; public final String TYPE_ZLX = "ZLX"; public final String TYPE_FP = "FP"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dhms1); editText1 = (EditText) findViewById(R.id.et1); editText2 = (EditText) findViewById(R.id.et2); bt1 = (Button) findViewById(R.id.bt1); //类型 bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { double numA = Double.valueOf(editText1.getText().toString()); int numB = Integer.valueOf(editText2.getText().toString()); YunSuanIpm2 yst = new YunSuanIpm2(TYPE_FP, numA, numB); } }); } }
优化之后,不单单是把静态对象的隐患给消除了,而且还加强了解耦。