<style> /* basic design */ .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6, .reveal section, .reveal table, .reveal li, .reveal blockquote, .reveal th, .reveal td, .reveal p { font-family: 'Meiryo UI', 'Source Sans Pro', Helvetica, sans-serif, 'Helvetica Neue', 'Helvetica', 'Arial', 'Hiragino Sans', 'ヒラギノ角ゴシック', YuGothic, 'Yu Gothic'; text-align: left; line-height: 1.6; letter-spacing: normal; text-shadow: none; word-wrap: break-word; color: #444; } .reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 {font-weight: bold;} .reveal h1, .reveal h2, .reveal h3 {color: #2980b9;} .reveal th {background: #DDD;} .reveal section img {background:none; border:none; box-shadow:none; max-width: 95%; max-height: 95%;} .reveal blockquote {width: 90%; padding: 0.5vw 3.0vw;} .reveal table {margin: 1.0vw auto;} .reveal code {line-height: 1.2;} .reveal p, .reveal li {padding: 0vw; margin: 0vw;} .reveal .box {margin: -0.5vw 1.5vw 2.0vw -1.5vw; padding: 0.5vw 1.5vw 0.5vw 1.5vw; background: #EEE; border-radius: 1.5vw;} /* table design */ .reveal table {background: #f5f5f5;} .reveal th {background: #444; color: #fff;} .reveal td {position: relative; transition: all 300ms;} .reveal tbody:hover td { color: transparent; text-shadow: 0 0 3px #aaa;} .reveal tbody:hover tr:hover td {color: #444; text-shadow: 0 1px 0 #fff;} /* blockquote design */ .reveal blockquote { width: 90%; padding: 0.5vw 0 0.5vw 6.0vw; font-style: italic; background: #f5f5f5; } .reveal blockquote:before{ position: absolute; top: 0.1vw; left: 1vw; content: "\f10d"; font-family: FontAwesome; color: #2980b9; font-size: 3.0vw; } /* font size */ .reveal h1 {font-size: 5.0vw;} .reveal h2 {font-size: 4.0vw;} .reveal h3 {font-size: 2.8vw;} .reveal h4 {font-size: 2.6vw;} .reveal h5 {font-size: 2.4vw;} .reveal h6 {font-size: 2.2vw;} .reveal section, .reveal table, .reveal li, .reveal blockquote, .reveal th, .reveal td, .reveal p {font-size: 2.2vw;} .reveal code {font-size: 1.6vw;} /* new color */ .red {color: #EE6557;} .blue {color: #16A6B6;} /* split slide */ #right {left: -18.33%; text-align: left; float: left; width: 50%; z-index: -10;} #left {left: 31.25%; text-align: left; float: left; width: 50%; z-index: -10;} </style> <style> /* specific design */ .reveal h2 { padding: 0 1.5vw; margin: 0.0vw 0 2.0vw -2.0vw; border-left: solid 1.2vw #2980b9; border-bottom: solid 0.8vw #d7d7d7; } </style> <!-- --------------------------------------------------------------------------------------- --> # Rust勉強会 第18回 ## 17章 ### 2020/12/4 岡本拓海 --- ## 本日のメニュー 1. オブジェクト指向言語の特徴 2. トレイトオブジェクトで異なる型の値を許容する 3. オブジェクト指向デザインパターンを実装する プレゼン25分くらい+議論5分位で18:30前後終了を目指します。 --- ## オブジェクト指向言語の特徴 オブジェクト指向プログラムとは? GoFの定義によると >オブジェクト指向プログラムは、オブジェクトで構成される。オブジェクトは、 データとそのデータを処理するプロシージャを梱包している。このプロシージャは、 典型的にメソッドまたはオペレーションと呼ばれる。 ---- ## Rustはオブジェクト指向? - データ - 構造体 - enum - データを処理するプロージャ - implブロックで実装されるメソッド Rustはオブジェクト指向言語! ---- ## 継承が選択される理由 - コードを再利用したい - 親の型と同じ個所で子供の型を使用したい ---- ## 継承の悪いところ - コードを再利用したい - 設計によっては親や子供のコードが肥大化しがち - 継承の制限によってより設計の柔軟性が下がる(Javaとか) - 親の型と同じ個所で子供の型を使用したい ---- ## Rustのポリモーフィズム ポリモーフィズム(polymorphism):多相性 多態性 >Rustはサブクラスの代わりにジェネリクスを使用して様々な可能性のある型を抽象化し、トレイト境界を使用してそれらの型が提供するものに制約を課します。 これは時に、パラメータ境界多相性(bounded parametric polymorphism)と呼ばれます。 --- ## トレイトオブジェクトで異なる型の値を許容する >ライブラリの使用者が特定の場面で合法になる型のセットを拡張できるようにしたくなることがあります。 GUIライブラリの実装例を見ていきましょう ---- ## 一般的なふるまいをトレイトに定義する Drawトレイト ```rust= pub trait Draw { fn draw(&self); } ``` Drawトレイト実装する**トレイトオブジェクト**(```Box<Draw>```) ```rust= pub struct Screen { pub components: Vec<Box<Draw>>, } ``` ---- ## Screenの実装を考えてみる ```rust= pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<Draw>>, } impl Screen { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } ``` ↓この方法はあまりよくない。Tの型が1つに制限されてしまう。。。 ```rust= pub struct Screen<T: Draw> { pub components: Vec<T>, } impl<T> Screen<T> where T: Draw { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } ``` ---- ## トレイトを実装する Button型の実装を考える ```rust= pub struct Button { pub width: u32, pub height: u32, pub label: String, } impl Draw for Button { fn draw(&self) { // code to actually draw a button // 実際にボタンを描画するコード } } ``` ---- ```rust= extern crate gui; use gui::Draw; struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { // code to actually draw a select box //セレクトボックスを実際に描画するコード } } ``` ---- ## あ ```rust= use gui::{Screen, Button}; fn main() { let screen = Screen { components: vec![ Box::new(SelectBox { width: 75, height: 10, options: vec![ // はい String::from("Yes"), // 多分 String::from("Maybe"), // いいえ String::from("No") ], }), Box::new(Button { width: 50, height: 10, // 了解 label: String::from("OK"), }), ], }; screen.run(); } ``` ---- ## トレイトオブジェクトは、ダイナミックディスパッチを行う >単相化の結果吐かれるコードは、 スタティックディスパッチを行い、これは、コンパイル時にコンパイラがどのメソッドを呼び出しているかわかる時のことです。 これは、ダイナミックディスパッチとは対照的で、この時、コンパイラは、コンパイル時にどのメソッドを呼び出しているのかわかりません。 ダイナミックディスパッチの場合、コンパイラは、どのメソッドを呼び出すか実行時に弾き出すコードを生成します ― コンパイラがコードのインライン化するのを実効速度の向上がしにくくなる。 コードの柔軟性とのトレードオフなので、使用時は要検討 ---- ## トレイトオブジェクトには、オブジェクト安全性が必要 ```rust= pub trait Clone { fn clone(&self) -> Self; } ``` ```rust= pub struct Screen { pub components: Vec<Box<Clone>>, } ``` --- ## オブジェクト指向デザインパターンを実装する 以下の内容を実装してみましょう。(それっぽいかはさておき。。。) 1. ブログ記事は、空の草稿から始まる。 1. 草稿ができたら、査読が要求される。 1. 記事が承認されたら、公開される。 1. 公開されたブログ記事だけが表示する内容を返すので、未承認の記事は、誤って公開されない。 ---- ## デモコード ```rust= extern crate blog; use blog::Post; fn main() { let mut post = Post::new(); // 今日はお昼にサラダを食べた post.add_text("I ate a salad for lunch today"); assert_eq!("", post.content()); post.request_review(); assert_eq!("", post.content()); post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` ---- ## Postを定義し、草稿状態で新しいインスタンスを生成する ```rust= pub struct Post { state: Option<Box<State>>, content: String, } impl Post { pub fn new() -> Post { Post { state: Some(Box::new(Draft {})), content: String::new(), } } } trait State {} struct Draft {} impl State for Draft {} ``` ---- ## 記事の内容のテキストを格納する ```rust= pub struct Post { content: String, } impl Post { // --snip-- pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } } ``` ---- ## 草稿の記事の内容は空であることを保証する ```rust= impl Post { // --snip-- pub fn content(&self) -> &str { "" } } ``` ---- ## 記事の査読を要求すると、状態が変化する ```rust= impl Post { // --snip-- pub fn request_review(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } } trait State { fn request_review(self: Box<Self>) -> Box<State>; } struct Draft {} impl State for Draft { fn request_review(self: Box<Self>) -> Box<State> { Box::new(PendingReview {}) } } struct PendingReview {} impl State for PendingReview { fn request_review(self: Box<Self>) -> Box<State> { self } ``` ---- ## contentの振る舞いを変化させるapproveメソッドを追加する ```rust= impl Post { // --snip-- pub fn approve(&mut self) { if let Some(s) = self.state.take() { self.state = Some(s.approve()) } } } trait State { fn request_review(self: Box<Self>) -> Box<State>; fn approve(self: Box<Self>) -> Box<State>; } struct Draft {} impl State for Draft { // --snip-- fn approve(self: Box<Self>) -> Box<State> { self } } struct PendingReview {} impl State for PendingReview { // --snip-- fn approve(self: Box<Self>) -> Box<State> { Box::new(Published {}) } } struct Published {} impl State for Published { fn request_review(self: Box<Self>) -> Box<State> { self } fn approve(self: Box<Self>) -> Box<State> { self } } ``` ---- ## contentの振る舞いを変化させるapproveメソッドを追加する ```rust= impl Post { // --snip-- pub fn content(&self) -> &str { self.state.as_ref().unwrap().content(&self) } // --snip-- } ``` ---- ## h2 ```rust= trait State { // --snip-- fn content<'a>(&self, post: &'a Post) -> &'a str { "" } } // --snip-- struct Published {} impl State for Published { // --snip-- fn content<'a>(&self, post: &'a Post) -> &'a str { &post.content } } ``` ---- ## ステートパターンの代償 - 状態が状態間の遷移を実装しているので、状態の一部が密に結合した状態になってしまう - PendingReviewとPublishedの間に、Scheduledのような別の状態を追加したら、 代わりにPendingReviewのコードをScheduledに遷移するように変更しなければならない - ロジックの一部を重複させてしまう - 重複を除くためには、 Stateトレイトのrequest_reviewとapproveメソッドにselfを返すデフォルト実装する? - これ↑はオブジェクト安全性を侵害する ---- ## 状態と振る舞いを型としてコード化する ```rust= fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); assert_eq!("", post.content()); } ``` ---- ## 状態と振る舞いを型としてコード化する ```rust= pub struct Post { content: String, } pub struct DraftPost { content: String, } impl Post { pub fn new() -> DraftPost { DraftPost { content: String::new(), } } pub fn content(&self) -> &str { &self.content } } impl DraftPost { pub fn add_text(&mut self, text: &str) { self.content.push_str(text); } } ``` ---- ## 遷移を異なる型への変形として実装する ```rust= impl DraftPost { // --snip-- pub fn request_review(self) -> PendingReviewPost { PendingReviewPost { content: self.content, } } } pub struct PendingReviewPost { content: String, } impl PendingReviewPost { pub fn approve(self) -> Post { Post { content: self.content, } } } ``` ---- ## ブログ記事ワークフローの新しい実装を使うmainの変更 ```rust= extern crate blog; use blog::Post; fn main() { let mut post = Post::new(); post.add_text("I ate a salad for lunch today"); let post = post.request_review(); let post = post.approve(); assert_eq!("I ate a salad for lunch today", post.content()); } ``` --- ## 参考資料 https://doc.rust-jp.rs/book/second-edition/ch17-00-oop.html --- # ご清聴ありがとうございました
{"metaMigratedAt":"2023-06-15T16:34:46.922Z","metaMigratedFrom":"YAML","title":"第18回 17章","breaks":true,"description":"Rust勉強会第18回のスライド","slideOptions":"{\"theme\":\"white\",\"slideNumber\":\"c/t\",\"center\":false,\"transition\":\"none\",\"keyboard\":true}","contributors":"[{\"id\":\"610cfd52-ad2b-46e8-81e2-a79a85a7f06f\",\"add\":15498,\"del\":4539}]"}
    197 views