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