DAO模式代码阅读及应用

DAO模式代码阅读及应用

1. StudenDaoListImpl.java与StudentDaoArrayImpl.java有何不同?

  1. StudenDaoListImpl.java里使用链表存储元素,而StudentDaoArrayImpl.java里使用数组存储元素

2. StudentDao.java文件是干什么用的?为什么里面什么实现代码都没有?

  1. StudentDao.java文件用来定义接口StudentDao,里面包含接口StudentDao定义的抽象方法。因为这些方法会交由实现了StudentDao接口的类来实现,接口可以定义行为但是不定义操作。

3. 使用搜索引擎搜索“Java DAO”,选出几句你能看懂的、对你最有启发的话。请结合接口知识去理解。

  1. 来自https://www.runoob.com/note/27029的一些语句

    1、DAO接口: 把对数据库的所有操作定义成抽象方法,可以提供多种实现。(我的理解:DAO接口就是将针对数据库的所有操作共性定义成抽象方法,之后由其实现类来实现)

    2、DAO 实现类: 针对不同数据库给出DAO接口定义方法的具体实现。(我的理解:实现DAO接口的子类)

4. 尝试运行Test.java。根据注释修改相应代码。结合参考代码回答使用DAO模式有什么好处?

1. 运行截图

2. 使用DAO模式的好处:

  1. 在数据层的代码中,由于此时是面向接口编程,我们只考虑接口定义的操作,我们只需要关心怎样将数据写入和取出,我们不需要考虑后台的数据结构和整体架构是什么。有利于将数据访问的代码与后台代码相分离,降低了代码的耦合性,便于后台代码的修改与维护,方便进行代码分工

5. 可选:编写一些使用DAO模式的代码。比如使用文件作为购物车存储底层,如下,默认用户不可能直接对存储购物车信息的文件进行修改,而购物车可能本来就不是清空状态,购物车小组成员:林洁颖,庄昭和,宋思坡,漆靖

1. Commodity.java

package shopping;

public class Commodity {
	private Integer id;
	private String name;
	private Double price;
	private String description;

	
	public Commodity(Integer id, String name, double price, String description) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.description = description;
	}
	@Override
	public String toString() {
		return id + "    "+ name + "    " + price + "    " + description;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((description == null) ? 0 : description.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((price == null) ? 0 : price.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Commodity other = (Commodity) obj;
		if (description == null) {
			if (other.description != null)
				return false;
		} else if (!description.equals(other.description))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (price == null) {
			if (other.price != null)
				return false;
		} else if (!price.equals(other.price))
			return false;
		return true;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	
}

2. ShoppingCart.java(ShoppingCartDao的实现类)

package shopping;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ShoppingCart implements ShoppingCartDao{
	private List<ItemEntry> itemList;
	private String pathname="D:\ShoppingCart.txt";
	private File file;
	/**
	 * 购物车构造函数
	 */
	public ShoppingCart() {
		itemList = new ArrayList<ItemEntry>();
		file=new File(pathname);
		//创建一个存储购物车信息的文件对象,默认文件路径在D:ShoppingCart.txt
		try {
			//BufferedReader(FileReader("filename"))将FileReader包装后,再使用read(char[] chbf)读取,可以将文件内容装入缓存。
            FileReader fr = new FileReader(pathname);
            BufferedReader bf = new BufferedReader(fr);
            String str[];
            String temp;
            while (( temp= bf.readLine()) != null) {
            	//去除读入字符串的空格
                str=temp.split("\s+");
                Integer id = Integer.valueOf(str[0]);
                String name = str[1];
				double price = Double.valueOf(str[2]);
				String description =str[3];
				int number=Integer.valueOf(str[4]);
				addItemEntry( new Commodity(id, name, price, description),number);
            }
            //关闭资源
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
		
	}
	/**
	 * 对文件内容进行重写
	 * 将itemList的内容按行写入文件中
	 * @throws Exception
	 */
	private  void changeFile()  {
			if (!file.isFile()) {
	            try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        BufferedWriter writer = null;
			try {
				writer = new BufferedWriter(new FileWriter(pathname));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        for (ItemEntry itemEntry:itemList){
	            try {
					writer.write(itemEntry + "
");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}

	/**
	 * 往购物车里面存放商品。 如果该类商品未存在购物车条目中,新建一个购物车条目 如果该类商品已存在购物车条目中,该类商品的购物车条目的商品数量+1
	 * 
	 * @param item
	 */
	
	public void add(Commodity item) {
		if (item == null) {
			return;
		}
		int index = findItemEntry(item);
		if (index == -1) {
			itemList.add(new ItemEntry(item));
			try {
				changeFile();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			itemList.get(index).increase();
			try {
				changeFile();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 从购物车减少某类商品number
	 * 
	 * @param item
	 * @return 1.如果该类商品未存在购物车条目中,return false 2.如果该类商品已存在购物车条目中,该类商品的购物车条目的商品数量-1
	 */
	public boolean remove(Commodity item) {
		if (item == null) {
			return false;
		}
		int index = findItemEntry(item);
		if (index == -1) {
			return false;
		}

		else {
			if (itemList.get(index).number <= 1) {
				itemList.remove(index);
			}
			itemList.get(index).decrease();
			try {
				changeFile();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
	}

	/**
	 * 从购物车条目直接移除某类商品
	 * 
	 * @param item
	 * @return 1. 如果该类商品未存在购物车条目中,return false 2.如果该类商品已存在购物车条目中,移除该商品条目
	 */
	public boolean removeItemEntry(Commodity item) {
		if (item == null) {
			return false;
		}
		int index = findItemEntry(item);

		if (index == -1) {
			return false;
		}

		else {
			itemList.remove(index);
			try {
				changeFile();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
	}
	/**
	 * 从购物车条目直接增加一个条目
	 * 
	 * @param item
	 * @return 1. 如果该类商品已存在购物车条目中,对应购物车条目的number数+ addNumber2.如果该类商品未存在购物车条目中,增加该商品条目
	 */
	public void  addItemEntry(Commodity item,int addNumber) {
		int index = findItemEntry(item);
		if (index ==-1) {
				itemList.add(new ItemEntry(item));
				itemList.get(findItemEntry(item)).number+=addNumber-1;
		}

		else {
			itemList.get(index).number+=addNumber;
		}
		try {
			changeFile();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	/**
	 * 在购物车中查找是否已存在相关条目 声明为private
	 * 
	 * @param item
	 * @return 如果包含返回相关条目所在下标,否则返回-1
	 */
	private int findItemEntry(Commodity item) {
		for (int i = 0; i < itemList.size(); i++) {
			if (itemList.get(i).getItem().equals(item)) {
				return i;
			}

		}
		return -1;

	}

	/**
	 * 展示购物车内容
	 */
	public void show() {
		System.out.println("显示购物车内容");
		System.out.println("========================================");
		System.out.println("id===商品名称===价格===商品描述===商品数量");
		
		for (ItemEntry itemEntry : itemList) {
			System.out.println(itemEntry);
		}
		System.out.println();
	}

	/**
	 * 获得购物车内商品的数量
	 * 
	 * @return 购物车内商品的数量
	 */
	public int getQty() {
		int sumNumber = 0;
		for (int i = 0; i < itemList.size(); i++) {
			sumNumber += itemList.get(i).number;

		}
		return sumNumber;
	}

	/**
	 * 结算
	 * 
	 * @return 返回购物车中所有商品的总价
	 */
	public double checkout() {
		double sumPrice = 0;
		for (ItemEntry itemEntry : itemList) {
			sumPrice += itemEntry.number * itemEntry.item.getPrice();
		}
		return sumPrice;
	}
	/**
	 * 清空购物车
	 */
	@Override
	public void clear() {
		itemList.clear();
		changeFile();
		
	}

	/**
	 * ShoppingCart内类商品购物车条目链
	 */
	class ItemEntry {

		/**
		 * 商品
		 */
		Commodity item;
		/**
		 * 商品数量
		 */
		int number;

		public ItemEntry(Commodity item) {
			super();
			this.item = item;
			this.number = 1;
		}
		// 商品数量添加
		public void increase() {
			number++;
		}
		// 商品数量减少
		public void decrease() {
			number--;
		}
		//获取商品
		public Commodity getItem() {
			return item;
		}
		//获取商品数量
		public int getNumber() {
			return number;
		}

		@Override
		public String toString() {
			return item+"    "+number;
		}

	}

	

}

3. ShoppingCartDao.java

package shopping;

public interface ShoppingCartDao {
	public void add(Commodity item);
	public boolean remove(Commodity item);
	public boolean removeItemEntry(Commodity item) ;
	public void  addItemEntry(Commodity item,int addNumber);
	public void show();
	public int getQty();
	public double checkout();
    public void clear();
	

}

4. Main.java(测试代码)

package shopping;

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Commodity x1 = new Commodity(1, "phone",1000.0,"苹果的");
		Commodity x2 = new Commodity(1, "phone",1000.0,"苹果的");
		Commodity x3 = new Commodity(2, "book",20.0,"java");
		Commodity x4 = new Commodity(3, "TV",1000.0,"AOC");
		
		/*添加*/
		ShoppingCart cart = new ShoppingCart();
		cart.add(x1);
		cart.add(x2);
		cart.add(x3);
		cart.show();
		
		/*删除-数量减少*/
		System.out.println("减少一件商品的数量");
		cart.remove(x1);
		cart.show();
		
		/*移除购物车条目*/
		System.out.println("减少一类商品的数量条目");
		cart.removeItemEntry(x1);
		cart.show();
		
		/*增加购物车条目*/
		System.out.println("增加一类商品的数量条目");
		int number=3;
		// 增加的一类商品一次性数量增加3
		cart.addItemEntry(x4, number);
		cart.show();
		
		/*计算商品总价和数量*/
		System.out.println("展示这时候所有购物车条目");
		cart.show();
		System.out.println("数量"+cart.getQty());
		System.out.println("总价:"+cart.checkout());
        
        /*清空购物车*/
		//cart.clear();
		//cart.show();
		
	}

}

5.部分输出内容(输出太长了就不全截了)及文件信息

6. 代码下载

代码下载

原文地址:https://www.cnblogs.com/tylk/p/13871530.html