1.抽象類應(yīng)用—模板方法模式
模板方法模式(Templete Method):定義一個操作中的算法的骨架驮宴,而將一些可變補(bǔ)分的實現(xiàn)延遲到子類中逮刨。模板方法使得子類可以不改變一個算法的結(jié)構(gòu)即可重新定義該算法的某些特定的步驟。
例如:
定義抽象類驗證管理員
子類實現(xiàn)抽象方法
2.接口應(yīng)用—策略模式
策略模式(Strategy Pattern )堵泽,定義了一系列算法禀忆,將每一種算法封裝起來并可以相互替換使用臊旭,策略模式讓算法獨立于使用它的客戶應(yīng)用而獨立變化。
OO設(shè)計原則:
1箩退、面向接口編程(面向抽象編程)
2离熏、封裝變化
3、多用組合戴涝,少用繼承
代碼示例:
package com.test;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User();
user.setISave(new NetSave());
user.add("users");
}
}
interface ISave{
public void Save(String data);
}
//文件類繼承ISave接口滋戳,實現(xiàn)將數(shù)據(jù)保存到文件中
class FileSave implements ISave{
public void Save(String data) {
System.out.println("保存到文件中..."+data);
}
}
class NetSave implements ISave{
@Override
public void Save(String data) {
// TODO Auto-generated method stub
System.out.println("保存文件到網(wǎng)絡(luò)中..."+data);
}
}
abstract class BaseService{
private ISave isave;
public void setISave(ISave isave){
this.isave = isave;
}
public void add(String data){
System.out.println("檢查數(shù)據(jù)合法性...");
isave.Save(data);
System.out.println("數(shù)據(jù)保存完畢");
}
}
class User extends BaseService{
}
3.簡單工廠模式
簡單工廠模式是由一個工廠對象 決定創(chuàng)建出哪一種產(chǎn)品的示例。簡單工廠模式是工廠模式家族中最簡單實用的模式啥刻。
package com.test;
public class simplefactory {
public static void main(String[] args) {
//使用者和被使用者兩者之間奸鸯,耦合,產(chǎn)生了依賴可帽,當(dāng)被使用者改變時娄涩,會影響使用者
//實用工廠模式來降低兩者之間的依賴
Product p = new ProductFactory().getProduct("Computer");
p.work();
}
}
//工廠類
class ProductFactory{
public Product getProduct(String name){
if("Phone".equals(name)){
return new Phone();
}else if("Computer".equals(name)){
return new Computer();
}else{
return null;
}
}
}
//工廠接口
interface Product{
public void work();
}
//手機(jī)
class Phone implements Product{
public void work(){
System.out.println("手機(jī)開始工作了");
}
}
//電腦
class Computer implements Product{
public void work() {
System.out.println("電腦開始工作了");
}
}