肖生克的救赎

        有一次,在看面向对象编程思想的时候,猛的想起肖生克的救赎的一个开头片段。安迪的老婆出轨了,安迪回家的时候正好撞见了他们在床上,安迪拿起枪杀死了他们。这个情景很适合用对象去描述。废话不多说,贴代码。


package com.lyc.pojo;

public class Gun {
	public void kill(Person person){ // 枪的一个杀人方法
		System.out.println(person.getName()+"被杀死了");
		person = null;
	}
}
package com.lyc.pojo;

import java.util.ArrayList;
import java.util.List;

public class Person {
	private String name;
	private String gender;
	private Gun gun ;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public Gun getGun() {
		return gun;
	}
	public void setGun(Gun gun) {
		this.gun = gun;
	}
	
	public void goBed(Bed bed){ // 人的一个上床动作
		List<Person> list = bed.getList() ; 
		if(list == null){
			list = new ArrayList<>(); 
			bed.setList(list);
		}
		bed.getList().add(this);
	}
	
	public void kill(Person person){ // 要杀人得利用枪
		if(gun == null){
			System.out.println(this.getName()+"没有枪");
		}
		gun.kill(person);
	}
	
	public void findHouse(House house){ // 杀人原因是床上有一男一女,一个还是自己的老婆,掏出枪干了男的,女的留下
		List<Person> list = house.getBed().getList();
		if(list.size() == 2 && !list.get(0).getGender().equals(list.get(1).getGender())){
			if("男".equals(list.get(0).getGender())){
				kill(list.get(0));
			}else{
				kill(list.get(1));
			}
		}else{
			System.out.println("没有什么事");
		}
	}
	public Person(String name, String gender, Gun gun) {
		super();
		this.name = name;
		this.gender = gender;
		this.gun = gun;
	}
	
	public Person(){
		super();
	}
}
package com.lyc.pojo;

import java.util.List;

public class Bed {
	private List<Person> list ; // 床上能容纳一定数目的人

	public List<Person> getList() {
		return list;
	}

	public void setList(List<Person> list) {
		this.list = list;
	}
	
}

package com.lyc.pojo;

public class House {
	private Bed bed ; // 房子里有床

	public Bed getBed() {
		return bed;
	}

	public void setBed(Bed bed) {
		this.bed = bed;
	}

	public House(Bed bed) {
		super();
		this.bed = bed;
	}
	
	public House(){
		super();
	}
}
package com.lyc.run;

import com.lyc.pojo.Bed;
import com.lyc.pojo.Gun;
import com.lyc.pojo.House;
import com.lyc.pojo.Person;

public class Run {
	public static void main(String[] args) { // 故事发展的主线
		Gun gun = new Gun();
		Person andy = new Person("andy","男",gun); 
		Person marry = new Person("marry","女",null);
		Person tom = new Person("tom","男",null);
		Bed bed = new Bed();
		House house = new House(bed);
		marry.goBed(bed);
		tom.goBed(bed);
		andy.findHouse(house);
	}
}

运行结果:


把tom.goBed(bed);注释掉



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值