Last active: 2 years ago
interface Draw {
draw(): void;
}
class Size {
constructor(public width: number, public height: number) {}
}
class Button implements Draw {
size: Size;
constructor(width: number, height: number, public label: string) {
this.size = new Size(width, height);
}
draw() {
console.log(
`Drawing button width: ${this.size.width} height: ${this.size.height} with label: ${this.label}`
);
}
}
class Input implements Draw {
size: Size;
constructor(width: number, height: number, public value: string) {
this.size = new Size(width, height);
}
draw() {
console.log(
`Drawing input width: ${this.size.width} height: ${this.size.height} with value: ${this.value}`
);
}
}
class MyScreen {
constructor(public components: Draw[]) {}
run() {
this.components.forEach((component) => {
component.draw();
});
}
}
const button = new Button(100, 44, "Submit");
const input = new Input(200, 44, "");
const screen = new MyScreen([button, input]);
screen.run();
export {};
trait Draw {
fn draw(&self) {}
}
struct Size {
pub width: u32,
pub height: u32,
}
struct Button {
pub label: String,
pub size: Size,
}
impl Draw for Button {
fn draw(&self) {
println!(
"Drawing button width: {} and height: {} with label: {}",
self.size.width, self.size.height, self.label
);
}
}
impl Clone for Button {
fn clone(&self) -> Self {
Self {
size: Size { ..self.size },
label: self.label.clone(),
}
}
}
impl Button {
pub fn new(width: u32, height: u32, label: String) -> Self {
Self {
size: Size { width, height },
label,
}
}
}
struct Input {
pub value: String,
pub size: Size,
}
impl Draw for Input {
fn draw(&self) {
println!(
"Drawing input width: {} and height: {} with value: {}",
self.size.width, self.size.height, self.value
);
}
}
impl Clone for Input {
fn clone(&self) -> Self {
Self {
size: Size { ..self.size },
value: self.value.clone(),
}
}
}
impl Input {
pub fn new(width: u32, height: u32, value: String) -> Self {
Self {
size: Size { width, height },
value,
}
}
}
struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
pub fn new(components: Vec<Box<dyn Draw>>) -> Self {
Self { components }
}
pub fn run(&self) {
let Self { components } = self;
// for component in components.iter() {
// component.draw()
// }
components.iter().for_each(|component| component.draw())
}
}
enum UIComponents {
Button(Button),
Input(Input),
}
fn other_draw(ui: &UIComponents) {
match ui {
UIComponents::Button(b) => b.draw(),
UIComponents::Input(i) => i.draw(),
}
}
fn main() {
let button = Button::new(100, 44, "Submit".to_string());
let input = Input::new(200, 44, "".to_string());
let screen = Screen::new(vec![Box::new(button.clone()), Box::new(input.clone())]);
screen.run();
let my_screen = vec![UIComponents::Button(button), UIComponents::Input(input)];
my_screen.iter().for_each(other_draw)
}