C# patterns subclasses -
i have class person
, 2 child classes staff
, student
, interface iperson
. have class database
, class gateway
. class database
has
private string id = "username";
and method
public void getid() {return id;}
both staff , student have getid() methods. gateway has check if method getid() requested staff
(return id
) or student
(return "go away!"
). can please me that. thinking using gateway
interface of database
class, because trying learn c#, don't know how that. or maybe there's better way of doing this... please thanks
here's code:
public class staff : person { public staff() {} public staff(string id): base(id) {} public override string getname() { throw new notimplementedexception(); } public override void update(object o) { console.writeline(id + " notified {1}", id, o.tostring()); } public override void updatemessage(object p) { console.writeline(id + " notified new message in chat: {1}", id, p.tostring()); } }
public class student : person { public student() {} public student(string id): base(id) {} public override string getname() { throw new notimplementedexception(); } public override void update(object o) { console.writeline(id +" notified {1}", id, o.tostring()); } public override void updatemessage(object p) { console.writeline("message " + id + " {1}", id, p.tostring()); } }
public abstract class person : iperson { string id; public person() { } public abstract string getname(); public person(string i) { this.id = i; } public abstract void update(object o); public abstract void updatemessage(object p); } public interface iperson { void update(object o); void updatemessage(object p); string getname(); }
class database { public string username = "username"; private string name = "user details"; private string grade = "user grade"; public string getname(object o) { if (o staff) { return name; } else { return "go away!"; } } public string getgrade() { return grade; } } public class gateway { public void dosomethingwithperson(iperson person) { string id = person.getname(); if (person student) { return "go away!"; } else if (person staff) { return name; } } }
i discourage is
chains altogether. violates liskov. in short, means hard add new iperson
implementation without modifying gateway
cope new type. or forces developers descend 1 of existing types implement new iperson
, in case, point of interface on abstract person
type?
public class gateway { public string dosomethingwithperson(iperson person) { return person.dosomething(); } } //then iperson implementors student can provide custom behaviour. public class student : person { public string dosomething() { return "go away!"; } ... }
Comments
Post a Comment